String word="i love apples i love orange";
String w=scan.next();
int index = word.indexOf(w);
System.out.println (index);
while (index >= 0) {
System.out.println(index);
index = word.indexOf(w, index + 1);
}
所以我知道这段代码会告诉我爱的索引是(2,17) 但我正在寻找的是,我希望它为我返回单词的索引(1,4),即它计算字符串中的字符串而不是字符......我还需要它来表示索引每次它发现它像上面那个感谢
答案 0 :(得分:2)
如果在您的变量“word”中单词仅使用空格分隔,则可以使用此类代码
String word="i love apples i love orange";
String w=scan.next();
String[] words = word.split(" ");
for (int i=0; i< words.length; i++){
if (words[i].equals(w)){
System.out.println(i);
}
}
更新: 如果你想数字,试试这个 -
String word="i love apples i love orange";
String w=scan.next();
String[] words = word.split(" ");
int count = 0;
for (int i=0; i< words.length; i++){
if (words[i].equals(w)){
System.out.println(i);
count ++;
}
}
System.out.println("Count = "+count);
答案 1 :(得分:0)
此代码查找单词中输入的位置以及单词在字符串中的位置。
public static void main(String[] args) {
int lastIndex = 0;
Scanner scan = new Scanner(System.in);
String w = scan.next();
String word = "i love apples i love orange";
String[] tokens = word.split(" ");
for (String token : tokens) {
if (token.contains(w)) {
for (int x = 0; x < token.length(); x++) {
System.out.println("Input found in token at position: " + (token.indexOf(w) + 1));
}
System.out.println("Word found containing input in positions: " + (word.indexOf(token, lastIndex) + 1)
+ "-" + ((word.indexOf(token, lastIndex)) + token.length()));
lastIndex = ((word.indexOf(token,lastIndex)) + token.length());
}
}
}
答案 2 :(得分:0)
此代码每次在段落(str)中找到字符串(针)。 针可以包含空格,每次都会打印单词索引。
String str = "i love apples i love orange";
String needle = "i love";
int wordIndex = 0;
for (int start = 0; start < str.length(); start++) {
if (Character.isWhitespace(str.charAt(start))) wordIndex++;
if (str.substring(start).startsWith(needle)) {
System.out.println(wordIndex);
}
}
答案 3 :(得分:-1)
package JavaPractice;
public class CountNumberOfWords {
public static void main(String[] args) {
String str = "My name is srikanth. srikanth is working on a java program. " +
"srikanth dont know how many errors atr there. so, " +
"srikanth is going to find it.";
String Iwant = "srikanth";
int wordIndex = 0;
int count =0;
for (int start = 0; start < str.length(); start++) {
if (Character.isWhitespace(str.charAt(start))) wordIndex++;
if (str.substring(start).startsWith(Iwant)) {
System.out.println("Index of the String Iwant "+wordIndex);
count++;
}
}
System.out.println("Number of times srikanth in str is="+count);
}
}
输出:
Index of the String Iwant 3 Index of the String Iwant 4 Index of the String Iwant 11 Index of the String Iwant 20 Number of times srikanth in str is=4