1

How would I get the indexes of of 'a'?

My current output : 5

    int freq = 0;
    String s = "Happy days are here again";
    char a = 'a';


    //processing
    for(int i = 0;i<=s.length()-1;i++){
        if(s.charAt(i)==a){
            freq++;
        }//end of if

    }//end of for
    System.out.println(freq);

Expected output: 1,7,11,20,22

  • What happens if you add a print statement inside your if-statement? – Jacob G. Dec 04 '19 at 20:37
  • 1
    Does this answer your question? [Indexes of all occurrences of character in a string](https://stackoverflow.com/questions/5034442/indexes-of-all-occurrences-of-character-in-a-string) – kamer Dec 04 '19 at 20:38

3 Answers3

0

This will do it. Just concatenate them to a string and print.


      String s = "Happy days are here again";
      char a = 'a';

      // processing
      String indices = "";
      for (int i = 0; i <= s.length() - 1; i++) {
         if (s.charAt(i) == a) {
            indices += (i + ",");
         } // end of
      } // end of for

      System.out.println(indices.substring(0, indices.length() - 1));

You can also put them in a list and print that out.

     List<Integer> indices = new ArrayList<>();
     indices.add(i);

Then later - System.out.println(indices):
WJS
  • 36,363
  • 4
  • 24
  • 39
0

Currently you are counting the instances of the letter a and printing the number of instances. If you want the indexes, I would recommend printing out your loop index i.

int freq = 0;
String s = "Happy days are here again";
char a = 'a';


//processing
for(int i = 0;i<=s.length()-1;i++){
    if(s.charAt(i)==a){
        System.out.print(i + ",");
    }//end of if

}//end of for
System.out.println(freq);

If your Expected Output is strictly enforced, then you will need to add additional logic to separate the indexes with commas.

Connor
  • 365
  • 3
  • 10
0

Maybe try to make an arraylist where you store the index of the character occurances?

ArrayList<Integer> answer = new ArrayList<Integer>;
for (int i = 0; i < s.length; i++) {
     if (s.charAt(i) == a) {
         answer.add(i);
     }
}

And then print the arraylist as you wish.