简体   繁体   English

如何用整数替换字符串中的字符?

[英]how to replace characters in a string with integers?

Say I have the the string: " aab + bab = b " and I want to 说我有字符串:“ aab + bab = b”,我想

  • replace all the a characters with the integer 0, 将所有a字符替换为整数0,
  • replace all the b characters with the integer 1 将所有b字符替换为整数1

so it will become: 因此它将变为:

001 + 101 = 1

what would be the easiest way to do this? 最简单的方法是什么?

so far I parced the equation into three parts: 到目前为止,我将等式分为三部分:

System.out.println("Enter an Equation of variables");
_inString = _in.nextLine();

    //find the three different parts of the equation
    String _noSpaces = _inString.replaceAll("\\s+","");
    String delims = "[+,=]";
    String[] _tokens = _noSpaces.split(delims);

You can chain replace methods together 您可以replace方法链接在一起

String str = " aab + bab = b ";
str = str.replace("a", "0").replace("b", "1");

We require an assignment back to 'str' because str.replace() returns a new String and the original string would be unchanged. 我们要求分配回'str',因为str.replace()返回一个新的String且原始字符串将保持不变。 [Because String is immutable in Java] [因为字符串在Java中是不可变的]

Do you only have binary operands? 您只有二进制操作数吗?

Just do 做就是了

replaceAll("a", "0");
replaceAll("b", "1");

Edit : 编辑

Since you want to evaluate your equation, I suggest you used the solution above, then use a java math parser. 由于您想评估方程式,因此建议您使用上述解决方案,然后使用Java数学解析器。 Several can be found after a quick googling. 快速浏览后,可以找到几个。

My favourite is Javaluator . 我最喜欢的是Javaluator

If you want to replace single characters with other single characters you can use 如果要用其他单个字符替换单个字符,可以使用
replace(char oldChar, char newChar) to avoid regex used in replace(char oldChar, char newChar)避免在中使用正则表达式

like 喜欢

_inString = _inString.replace('a', '0').replace('b', '1');

You could also do this: 您也可以这样做:

String s = aab + bab = b;

int i = 0;
int i2 = 1;

String ii = i + "";
String ii2 = i2 + "";

I use this because say 1 and 0 were not identified. 我之所以使用它,是因为未确定10 You could setup i and i2 to be changeable if your API/Platform supports it. 如果您的API /平台支持,则可以将ii2设置为可更改的。

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

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