【问题标题】:String to find A character [duplicate]查找A字符的字符串[重复]
【发布时间】:2014-03-09 09:46:38
【问题描述】:

我想在一个字符串中查找(A 个字符)。如果有一个 A 字符,则执行特定操作,如果字符串中有两个 AA,则执行其他特定操作。我怎样才能知道字符串有多少个 A 字符?

【问题讨论】:

标签: java android


【解决方案1】:
  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 表示字符串常量 ;)
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    遍历字符串中的每个字符,每次都测试该字符:

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

    那么count 将是在字符串中找到的As 的数量。

    【讨论】:

      【解决方案4】:
      String s = "some number of A characters in this AA string";
      System.out.println(s.length() - s.replaceAll("A","").length());
      

      结果:

      3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-20
        • 1970-01-01
        • 2012-11-30
        • 2014-05-09
        • 2020-02-24
        • 2016-10-08
        • 1970-01-01
        相关资源
        最近更新 更多