简体   繁体   English

如何从字符串中分隔数字和算术运算符?

[英]How to separate numbers and arithmetic operators from a string?

I have a string I need to read it and divide it to numbers and operations for a calculator. 我有一个字符串,我需要读取它并将其分为数字和计算器的操作。

For example: if the input is "22*432+33" 例如:如果输入为"22*432+33"

I need to console to take the string as whole and add the numbers in an array till it find operation signs and push the operation sign in another array so the output result: 我需要控制台将字符串作为整体并在数组中添加数字,直到找到操作符号并将操作符号推入另一个数组,以便输出结果:

numbers = ["22", "432", "33"];
operations = ["*", "+"];

The language I'm using is javascript I know the question may be board but I'm trying to solve it for a week with no success. 我正在使用的语言是javascript我知道问题可能是董事会,但我试图解决它一个星期没有成功。

One of my fails attempt: 我失败的尝试之一:

 var numbers = []; var tokens = ["+", "-", "/", "*"]; var textfield = "22*432+33"; for (var i = 0; i <= textfield.trim().length; i++) { if (tokens.includes(textfield[i]) == false) { numbers.push(textfield.split()); } } console.log(textfield); console.log(tokens); console.log(numbers); 

The output result: 输出结果:

在此输入图像描述

You can split your input into digits and non digits. 您可以将输入拆分为数字和非数字。

 const input = "22*432+33"; const numbers = input.split(/\\D/g); const op = input.split(/\\d/g).filter(Boolean); console.log(numbers); console.log(op); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM