-6

I want to find(A characters) in a string. if there is one A character, then specific operation is done and if there is two AA in string then other specific operation is done. How can i find out the string have how many A characters?

vik
  • 33
  • 1
  • 8

4 Answers4

4
  1. If you're beginner check this :

    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. If you're not beginner:

     String s="Good , I think so";
     int counter = s.split("A").length - 1;  //you can change A with your character
    
Zied R.
  • 4,964
  • 2
  • 36
  • 67
1

You didn't state if you are checking for 2 AAs and only 2 AAs. If the question is "more than one A", then:

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"
}
Simon
  • 14,407
  • 8
  • 46
  • 61
0

Iterate through every character in the string and test the character each time:

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

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

Then count would be the number of As found in the string.

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
0
String s = "some number of A characters in this AA string";
System.out.println(s.length() - s.replaceAll("A","").length());

Result:

3
xagyg
  • 9,562
  • 2
  • 32
  • 29