![](/img/trans.png)
[英]Return the number of times the string "hello/HELLO/hellO ..." appears anywhere in the given string
[英]Return the number of times that the string “hello” appears anywhere in the given string
public int count(String str){
int count=0;
int index=str.indexOf("Hello");
System.out.println(index);
while(index!=-1)
{
index=str.indexOf("Hello",index+1);
count++;
}
return count;
}
通过测试用例时出现问题。
Testcase Pass/Fail Parameters Actual Output Expected Output
#1 Pass 'Hello how are you' 1 1
#2 Fail 'HELLO how are you' 0 1
Java(极端)区分大小写。 Hello
与HELLO
。
您可以做的是将原始String
转换为小写,然后搜索hello
出现。
您错过了区分大小写的要点。
您可以尝试如下。
public static void main(String args[]) throws Exception {
System.out.println(count("Hello how are you"));
}
public static int count(String str) {
String[] arr=str.split(" ");
int count=0;
for(String i:arr){
if(i.equalsIgnoreCase("hello")){
count++;
}
}
return count;
}
尝试这个..
public int count(String str){
int count=0;
String str1="";
for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
if(ch>=65 && ch <=90){
ch=(char)(ch + 32);
str1=str1 + ch;
}
else
str1=str1+ch;
}
int index=str1.indexOf("hello");
System.out.println(index);
while(index!=-1)
{
index=str1.indexOf("hello",index+1);
count++;
}
return count;
}
如果您看到indexOf()
的源代码,它会通过将字符串转换为char数组来逐字符比较字符串,因此e
不等于E
并在那里失败。
使用java8流API:
private static long count(String string) {
return Arrays.asList(string.split(" ")).parallelStream().map(str -> str.toLowerCase())
.filter(str -> "hello".equals(str)).count();
}
public static void main(String args[]) {
String s1 = "Hello how are you";
System.out.println(Long.toString(count(s1)));
String s2 = "HELLO how are you";
System.out.println(Long.toString(count(s2)));
}
//返回字符串“ hello”出现在给定字符串中任意位置的次数。
公共类CountHello {static String testcase1 =“你好!你好!你好吗?”;
public static void main(String args[]){
CountHello testInstance= new CountHello();
int result = testInstance.count(testcase1);
System.out.println(result);
}
public int count(String str1){
//write your code here
String str2="Hello";
int len1=str1.length();
int len2=str2.length();
int count=0;
for(int i=0;i<(len1-len2+1);i++)
{ String str="";
for(int j=i;j<i+len2;j++)
{
str=str+str1.charAt(j);
if(str.equalsIgnoreCase(str2)) count++;
}
}
return count;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.