-5

I'm trying to count how many times the word "ing" occurred in a string asked by a user, I'm having an error saying it cannot be converted.

I tried using s.indexOf("ing")

package javaapplication3;

import java.util.*;

public class JavaApplication3 {


public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
    String s,q = null;
    String i = "ing";
    int count=0;
  System.out.println("Entrer une ligne de texte :");
  s = in.next();
  if ( s.indexOf("ing") ){
      count++;
  q = s.replaceAll("ing", "ed");
  }
  System.out.println("\"ing\" est occuree " +count +" fois.");
  System.out.println(q);
}
}

I expect the output would give me and count how many times it occurred but I'm having an error.

2 Answers2

1
  1. Use s = in.nextLine(); rather than next() to read the whole line

  2. You need to count until the lookFor part is still in the word, each time replace the first occurence by something else, and continue using a while loop

    String lookFor = "ing";
    while (s.indexOf(lookFor) != -1) {
        count++;
        s = s.replaceFirst(lookFor, "ed");
    }
    

    same as

    String lookFor = "ing";
    while (s.contains(lookFor)) {
        count++;
        s = s.replaceFirst(lookFor, "ed");
    }
    
azro
  • 53,056
  • 7
  • 34
  • 70
0

You should loop over your input till your string does not have the required literal available,

int count = 0;
while (s.indexOf("ing") != -1) {
    s = s.replaceFirst("ing", "");
    count++;
}
System.out.print("Total occurances : "+count);
ScanQR
  • 3,740
  • 1
  • 13
  • 30