要查找字符的字符串

时间:2014-03-09 09:46:39

标签: java android

我想在字符串中找到(A个字符)。如果有一个A字符,则进行特定操作,如果字符串中有两个AA,则完成其他特定操作。我如何找出字符串中有多少个A字符?

4 个答案:

答案 0 :(得分:4)

  1. 如果您是初学者,请检查:

    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);
    
  2. 如果你不是初学者:

     String s="Good , I think so";
     int counter = s.split("A").length - 1;  //you can change A with your character
    

答案 1 :(得分:1)

您没有说明您是否正在检查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"
}

答案 2 :(得分:0)

遍历字符串中的每个字符并每次测试字符:

String s = "foo bAr";
int count = 0;

for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == 'A') {
        count++;
    }
}

然后count将是字符串中找到的A的数量。

答案 3 :(得分:0)

String s = "some number of A characters in this AA string";
System.out.println(s.length() - s.replaceAll("A","").length());

<强>结果:

3