![](/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.