How to Detect commas within a string and print the number of commas as well as where the commas occured within the string

58 views Asked by At

I've tried using a for loop to detect the commas within the given input of "Gil,Noa,Guy,Ari" and then list the location of the commas within the string.

import java.util.Scanner;

public class FindCommas {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      String delimitedData;
      int i;
        int freqOccurred = 0;
   
      delimitedData = scnr.nextLine();
      
      for (i = 0; i < delimitedData.length(); ++i) {
         if (Character.isLetter(delimitedData.charAt(i))) {
         System.out.println("Comma found at index " + i);
         }
      }
      
      for(String subString: delimitedData.split(",")){
         freqOccurred = freqOccurred + 1;
      }
      freqOccurred = freqOccurred - 1;

    System.out.println("Comma occurs " + freqOccurred + " times");
    }
}

The output it produces currently is:

Comma found at index 0

Comma found at index 1

Comma found at index 2

Comma found at index 4

Comma found at index 5

Comma found at index 6

Comma found at index 8

Comma found at index 9

Comma found at index 10

Comma found at index 12

Comma found at index 13

Comma found at index 14

Comma occurs 3 times

The problem is that it skips the index location of where the commas are and I cannot figure out how to flip it to only produce the index of the commas rather than just the index of the letters.

Expected output:

Comma found at index 3

Comma found at index 7

Comma found at index 11

Comma occurs 3 times

note: code must not contain arrays

(sorry for the poor formatting of the post)

1

There are 1 answers

1
AtomicO5 On BEST ANSWER

Answer for those who want it:

   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      String delimitedData;
      int i;
        int freqOccurred = 0;
   
      delimitedData = scnr.nextLine();
      
      for (i = 0; i < delimitedData.length(); ++i) {
         if (delimitedData.charAt(i) == ',') {
            System.out.println("Comma found at index " + i);
         }
      }
      
      for(String subString: delimitedData.split(",")){
         freqOccurred = freqOccurred + 1;
      }
      freqOccurred = freqOccurred - 1;

    System.out.println("Comma occurs " + freqOccurred + " times");
    }
}