我在这里做错了吗?打印时,我得到“*”,我需要得到“-32”。我正在解析每个单词并返回最后一个单词。
public static void main(String[] args) {
System.out.println(stringParse("3 - 5 * 2 / -32"));
}
public static String stringParse(String string) {
String[] word = new String[countWords(string)];
string = string + " ";
for (int i = 0; i <= countWords(string); i++) {
int space = string.indexOf(" ");
word[i] = string.substring(0, space);
string = string.substring(space+1);
}
return word[countWords(string)];
}
public static int countWords(String string) {
int wordCount = 0;
if (string.length() != 0) {
wordCount = 1;
}
for (int i = 0; i <= string.length()-1; i++){
if (string.substring(i,i+1).equals(" ")) {
wordCount++;
}
}
return wordCount;
}
答案 0 :(得分:2)
您可以使用“\\ s +”将字符串拆分为空格,然后返回该数组的最后一个元素。这将返回最后一个字。
public static String stringParse(String s){
return s.split("\\s+")[s.split("\\s+").length-1];
}
答案 1 :(得分:0)
在这种情况下,您也可以使用正则表达式:
-Proxy