返回给定字符串中出现“hi”的次数。

3

我编写了以下Java代码,但它返回了一个超时错误。我不太确定这是什么意思,也不知道为什么代码无法运行。

public int countHi(String str) {
  int pos = str.indexOf("hi"); 
  int count = 0;
  while(pos!=-1)
  {
    count++;
    pos = str.substring(pos).indexOf("hi");
  }
  return count;
}

我知道另一种解决方案,可以使用for循环,但我认为这个方法也应该可以奏效。
3个回答

2
你陷入了一个无限循环,因为pos从未超过第一个匹配项,而第一个匹配项将包含在子字符串中。
你可以通过在while循环中使用这个重载版本的indexOf()来解决这个问题。
pos = str.indexOf("hi", pos + 1);

或者使用 do... while 循环,避免重复调用 indexOf() 方法:
public static int countHi(String str) {
    int pos = -1, count = -1;

    do {
        count++;
        pos = str.indexOf("hi", pos + 1);
    } while (pos != -1);

    return count;
}

1
输出从给定索引开始的子字符串。因此,在您的代码中,while循环永远不会遍历整个字符串,并且会在第一个“hi”处停止。使用这个。
while(pos!=-1){
   count++;
   str = str.substring(pos+2);
   pos = str.indexOf("hi");
}

str变量存储字符串的后半部分(使用+2来遍历两个以上的索引以到达“hi”的末尾),然后检查pos变量存储“hi”出现在新字符串中的索引。


0

只是为了增加乐趣......

如果要计算提供的子字符串(即:"hi")并且它出现在输入字符串中的位置不重要(可以是单词或单词的一部分),您可以使用一行代码,让 String.replace() 方法为您完成工作,实际上从初始输入字符串中删除您想要计数的所需子字符串,并计算该输入字符串的剩余部分(这不会修改初始输入字符串):

String inputString = "Hi there. This is a hit in his pocket";
String subString = "hi";
int count = (inputString.length() - inputString.replace(subString, "").
                length()) / subString.length())

//Display the result...
System.out.println(count);

控制台将显示:3

您会注意到上述代码区分大小写,因此在上面的示例中,子字符串"hi"与单词"Hi"不同,因为大写字母"H",所以忽略了"Hi"。如果要在计算提供的子字符串时忽略大小写,则可以使用相同的代码,但在其中利用 String.toLowerCase() 方法:

String inputString = "Hi there. This is a hit in his pocket";
String subString = "hi";
int count = (inputString.length() - inputString.toLowerCase().
             replace(substring.toLowerCase(), "").
             length()) / substring.length())

//Display the result...
System.out.println(count);

控制台将显示:4

如果您要计算的提供的子字符串是一个特定单词(而不是另一个单词的一部分),则会变得有些复杂。您可以通过利用 Pattern Matcher 类以及一个小的正则表达式来做到这一点。它可能看起来像这样:

String inputString = "Hi there. This is a hit in his pocket";
String subString =   "Hi";
String regEx = "\\b" + subString + "\\b";

int count = 0;  // To hold the word count
// Compile the regular expression
Pattern p = Pattern.compile(regEx);
// See if there are matches of subString within the 
// input string utilizing the compiled pattern
Matcher m = p.matcher(inputString);
// Count the matches found
while (m.find()) {
    count++;
}

//Display the count result...
System.out.println(count);

控制台将显示:1

同样,上述代码区分大小写。换句话说,如果提供的子字符串是"hi",则控制台中的显示将是0,因为"hi"与包含在输入字符串中的第一个单词"Hi"不同。如果您想忽略大小写,则只需将输入字符串和提供的子字符串转换为全大写或全小写即可,例如:

String inputString = "Hi there. This is a hit in his pocket";
String subString =   "this is";
String regEx = "\\b" + subString.toLowerCase() + "\\b";

int count = 0;  // To hold the word count
// Compile the regular expression
Pattern p = Pattern.compile(regEx);
// See if there are matches of subString within the 
// input string utilizing the compiled pattern
Matcher m = p.matcher(inputString.toLowerCase());
// Count the matches found
while (m.find()) {
    count++;
}

//Display the count result...
System.out.println(count);

控制台将显示:1

正如您在上面的两个最新代码示例中所看到的,正则表达式(RegEx)"\\bHi\\b"被使用了(在代码中,一个变量被用来代替Hi),这是它的含义:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接