简体   繁体   中英

In Java, how do I take a string that a user enters and count the number of times 2 specific lowercase letters come up in order?

So like if a string is, "I am going fishing"

So the number of times the lowercase letters "ng" come up in that specific order in this string is 2 times. And they have to be right next to each other, like no space between them.

So how do I do that? Please help. So whatever string a user enters, it must count the number of times "ng" comes up. Please help. Thanks!

JAVA

If you use regex, you only need one line:

int count = input.replaceAll("[^n]|n(?!g)", "").length();

This works by removing (by replacing with a blank), all characters that are either:

  • not an "n"
  • an "n" not followed by a "g"

The resulting String will contain one "n" for every "ng" in the original String, so the count is simply its length.

public int value()
{
String str = "I am going fishing";
String findStr = "ng";
int lastIndex = 0;
int count =0;

while(lastIndex != -1){

       lastIndex = str.indexOf(findStr,lastIndex);

       if( lastIndex != -1){
             count ++;
             lastIndex+=findStr.length();
      }
}
return count;
}

count is number of occurrence.

    Try this. Use Common Lang jar in your library :

     try {
                BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
                System.out.println("Enter the user String");
                String userString=br.readLine();
                System.out.println("Enter the search String");
                String searchString=br.readLine();

                int count = StringUtils.countMatches(userString, searchString);
                System.out.println("Value "+ count);

            } catch (IOException ex) {
                System.out.println("No Input");
            }

Output :

Enter the user String
Hello Mango Hello
Enter the search String
Hello
Value 2
String s="I am going fishing";
    System.out.println(s.length());
    int j=0;
    int cnt=0;
    for(int i=0;i<s.length();i++)
    {
        char i1=s.charAt(i);
        j=i+1;
        if((i1=='n')||(i1=='N'))
        {
            if((s.charAt(j)=='g')||((s.charAt(j)=='G')))
            {
                cnt=cnt+1;
                i=j;
            }
        }

    }
    System.out.println("Count of 'ng' is "+cnt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM