[英]How can I split a string as such…?
在我的編程課上,老師要求我們制造一個能以“數字功能數字”類型格式使用的計算器。 當編寫一種方法來檢查字符串是否有效時,我意識到它會在空格后停止檢查字符串。 如何繼續檢查? 我唯一的想法是將其拆分然后檢查,但是我不知道該怎么做,所以...
我如何分割這樣的字符串:
String s = "2345 * 2341";
通過以下方式:
String String1 = 2345;
String String2 = 2341;
然后,如何檢查每個字符串以確保其有效? 到目前為止,我有:(注意:我是編程的初學者)
public boolean validNumber() throws IOException {
input = getUserInput();
boolean valid = false;
int i = 0;
for (valid = true; i < input.length();) {
if (input.charAt(i) == '0'
&& input.charAt(i) == '1'
&& input.charAt(i) == '2'
&& input.charAt(i) == '3'
&& input.charAt(i) == '4'
&& input.charAt(i) == '5'
&& input.charAt(i) == '6'
&& input.charAt(i) == '7'
&& input.charAt(i) == '8'
&& input.charAt(i) == '9') {
valid = true;
}else{
valid = false;
}
i++;
}
return valid;
}
public void check() throws IOException {
boolean valid = validNumber();
int i = 0;
while (valid = true && i < 1){
if (input.contains(" + ")) {
plus();
} else if (input.contains(" - ")) {
minus();
} else if (input.contains(" / ")) {
divide();
} else if (input.contains(" * ")) {
multiply();
}else {
System.out.println("Error Incorrect Input");
System.out.println("Reinput your numbers");
}
check();
}
}
}
您可以使用split
方法拆分字符串。 若要檢查Long.parseLong
字符串是否有效,請使用Long.parseLong
方法。 如果字符串不是有效數字,則將引發NumberFormatException
。
String s = "2345 * 23s41";
String[] strings = s.split("\\*"); //Split strings
string1 = strings[0].trim();
string2 = strings[1].trim();
您可以通過以下方法檢查有效性:
public boolean isValid(String s)
{
try
{
Long.parseLong(s);
}
catch(NumberFormatException e)
{
return false;
}
return true;
}
您可以按如下方式拆分字符串,
String string = "1234*4321";
String[] strings = string.split("\\*");
String string1 = strings[0];
String string2 = strings[1];
如果要刪除空格,也可以執行以下操作,而不是修剪:
String s = "2345 * 2341";
String[] strings = s.split(" \\* ");
如果保證始終具有格式良好的字符串,格式為<operand1> <operator> <operand2>
,則可以按以下方式分隔不同部分:
String expression = "2345 * 2341";
String[] expressionParts = s.split(" ");
System.out.println(expressionParts[0].equals("2345")); //prints True
System.out.println(expressionParts[1].equals("*")); //prints True
System.out.println(expressionParts[2].equals("2341")); //prints True
下面是一個示例代碼:
String String1 = null;
String String2 = null;
String strNumber = "1234*4321";
String delimeter = "\\*";
if(strNumber != null)
{
String[] parts = strNumber.split(delimeter);
if(parts.length == 2)
{
String1 = parts[0];
String2 = parts[1];
}
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.