2
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),也就是说它很重要字符串中的字符串而不是字符......我也需要它来指示索引,每次它找到它就像上面的那个一样谢谢

4

4 回答 4

2

如果在您的变量“单词”单词中仅使用空格分隔,您可以使用这样的代码

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);
于 2013-01-05T10:28:50.177 回答
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());
        }
    }
}
于 2013-01-05T10:38:25.233 回答
0

此代码每次出现时都会在段落 (str) 中查找字符串 (needle)。针可以包含空格,每次都打印单词索引。

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);
  }
}
于 2013-01-05T10:47:11.177 回答
-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);

}
}

输出:

字符串索引 Iwant 3
字符串索引 Iwant 4
字符串索引 Iwant 11
字符串索引 Iwant 20
str 中 srikanth 的次数是=4
于 2015-04-26T04:55:44.800 回答