【发布时间】:2017-02-01 22:46:48
【问题描述】:
我在尝试分隔字符串中的单词时使用 indexOf() 查找空格,但索引关闭一直返回 -1;这是我的代码:-
import java.util.Scanner;
class Main {
public static void main(String[] args){
Scanner y = new Scanner(System.in);
System.out.println("Enter the String");
String s = y.nextLine();
int words = 1;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)==' ') words++;
}
String[] a = new String[words];
int l = s.length();
for (int i = 0; i <= words; i++) {
int r = s.indexOf(" ");
a[i] = s.substring(0, r);
s = s.substring((r + 1), l);
}
for(int i = 0; i <= words; i++) {
System.out.println(a[i]);
}
}
}
【问题讨论】:
-
这是你做过的minimal reproducible example吗?只需
System.out.println(s.indexOf(" "));就足够了;)。 PS:看String.split(String) -
@AxelH 不,因为只有这一行留下了太多的解释,例如
s的外观以及在调用indexOf()之前是否以及如何更改。 -
@AlexH 哦,拜托,这已经够小了,不,一行是不完整的。
-
s.indexOf(" ")是否最终返回 -1 或 _always,即第一次也是如此?您是否检查过输入中确实有空格,即您能否提供一些输入样本? -
@All,好吧,既然没有任何解释,对我来说这还不够。没有输入/输出的代码......所以你要么添加输入/输出,要么删除一些可能改变行为的复杂性......