【问题标题】:String and substring and how many times substring present in main string字符串和子字符串以及子字符串在主字符串中出现的次数
【发布时间】:2018-04-02 10:28:42
【问题描述】:

我在 Google 的一些解决方案的帮助下编写了代码。你能帮我详细了解一下while循环的作用吗?

import java.util.Scanner;

public class TwoStringsWordRepeat {
    public static void main(String[] args) {
        Scanner s = new Scanner (System.in);
        System.out.print("Enter Sentence: ");
        String sentence = s.nextLine();
        System.out.print("Enter word: ");
        String word = s.nextLine();
        int lastIndex = 0;
        int count = 0;
        while (lastIndex != -1) {
            lastIndex = sentence.indexOf(word, lastIndex);
            if (lastIndex != -1) {
                count++;
                lastIndex += word.length();
            }
        }
        System.out.println(count);
    }
}

解释一下while循环.indexOf();中的代码。

【问题讨论】:

  • indexOf() 查找wordsentence 中的第一个匹配项,根据urs 代码块中使用的变量从位置lastIndex 开始搜索。

标签: java string substring


【解决方案1】:

sentence.indexOf(word,lastIndex); 返回字符串word 的索引,从指定索引lastIndex 开始。否则将返回-1

它将在给定的sentence中搜索word,从给定的lastIndex开始

在代码中添加了 cmets。

// While we are getting the word in the sentence
// i.e while it is not returning -1
while(lastIndex != -1) {
    // Will get the last index of the searched word
    lastIndex = sentence.indexOf(word, lastIndex);

    // Will check whether word found or not 
    if(lastIndex != -1) {
        // If found will increment the word count
        count++;
        // Increment the lastIndex by the word lenght
        lastIndex += word.length();
    }
}

// Print the count
System.out.println(count);

【讨论】:

    【解决方案2】:

    indexOf() 返回给定子字符串在搜索字符串中第一次出现的偏移量,如果找不到相应的字符串,则返回-1

    使用替代语法,可以在给定偏移量处开始搜索,因此它只会在该特定起始偏移量之后找到匹配项。

    如果找到了word,那么它将进行另一次迭代,但在最后一次找到word 出现的末尾开始搜索

    【讨论】:

      猜你喜欢
      • 2010-10-20
      • 2021-02-10
      • 1970-01-01
      • 2020-02-21
      • 2012-02-12
      相关资源
      最近更新 更多