【发布时间】:2014-03-09 09:46:38
【问题描述】:
我想在一个字符串中查找(A 个字符)。如果有一个 A 字符,则执行特定操作,如果字符串中有两个 AA,则执行其他特定操作。我怎样才能知道字符串有多少个 A 字符?
【问题讨论】:
-
看看
String的方法的文档怎么样?
我想在一个字符串中查找(A 个字符)。如果有一个 A 字符,则执行特定操作,如果字符串中有两个 AA,则执行其他特定操作。我怎样才能知道字符串有多少个 A 字符?
【问题讨论】:
String的方法的文档怎么样?
如果您是初学者,请检查:
String s1=" read the documentation for the methods of String"; //your string
char ch=s1.charAt(s1.indexOf('A')); //first appearance of character A
int count = 0;
for(int i=0;i<s1.length();i++) {
if(s1.charAt(i)=='A'){ //if character at index i equals to 'A'
System.out.println("number of A:=="+ch);
count++; //increment count
}
}
System.out.println("Total count of A:=="+count);
如果您不是初学者:
String s="Good , I think so";
int counter = s.split("A").length - 1; //you can change A with your character
【讨论】:
您没有说明您检查的是 2 个 AA 还是仅 2 个 AA。如果问题是“不止一个A”,那么:
String s1=" read the documentation for the methods of String";
if(s1.replaceAll("A","").length() < s1.length()-1){
//this string has more than one "A"
}
【讨论】:
遍历字符串中的每个字符,每次都测试该字符:
String s = "foo bAr";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'A') {
count++;
}
}
那么count 将是在字符串中找到的As 的数量。
【讨论】:
String s = "some number of A characters in this AA string";
System.out.println(s.length() - s.replaceAll("A","").length());
结果:
3
【讨论】: