[英]how to replace characters in a string with integers?
說我有字符串:“ aab + bab = b”,我想
a
字符替換為整數0, b
字符替換為整數1 因此它將變為:
001 + 101 = 1
最簡單的方法是什么?
到目前為止,我將等式分為三部分:
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);
您可以replace
方法鏈接在一起
String str = " aab + bab = b ";
str = str.replace("a", "0").replace("b", "1");
我們要求分配回'str',因為str.replace()返回一個新的String且原始字符串將保持不變。 [因為字符串在Java中是不可變的]
您只有二進制操作數嗎?
做就是了
replaceAll("a", "0");
replaceAll("b", "1");
編輯 :
由於您想評估方程式,因此建議您使用上述解決方案,然后使用Java數學解析器。 快速瀏覽后,可以找到幾個。
我最喜歡的是Javaluator 。
如果要用其他單個字符替換單個字符,可以使用
replace(char oldChar, char newChar)
避免在中使用正則表達式
replace(CharSequence target, CharSequence replacement)
或 replaceAll(String regex, String replacement)
喜歡
_inString = _inString.replace('a', '0').replace('b', '1');
您也可以這樣做:
String s = aab + bab = b;
int i = 0;
int i2 = 1;
String ii = i + "";
String ii2 = i2 + "";
我之所以使用它,是因為未確定1
和0
。 如果您的API /平台支持,則可以將i
和i2
設置為可更改的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.