Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

how count the number of substrings in a string

807601Dec 31 2007 — edited Jan 3 2008
Hi all,

I wonder if someone can help me and point out where I'm going wrong.


I want to count the number of substring starting with 'd' and ending with 'e' in a string supplied by a user.

currently my code is only counting the number of 'd' and 'e' characters in the string.
{

    public static void main (String [] args) 
    
    {
    	Scanner input = new Scanner (System.in);
    	
    	
    	String mstring;// string variable that the user will enter
    	
    	int i = 0; // upstep variable
    	
    	int count = 0; // int variable to count the number of substrings
    	
    	System.out.print("Enter a string: ");
    	
    	
    	mstring = input.nextLine();
    	
    	
    	while (i != mstring.length())
    		
    		{
    			    			
    			if(mstring.charAt(i)=='d'){count++;}
    			
    			else if (mstring.charAt(i)=='e'){count++;}
    				
    			
    			i++;
    		}
    	
    	System.out.println("The total d e substrings is " + count);
    	
    }
    
    
}
For example if the user enters adbedeaadffe the total number of substrings should be 5 but I'm getting 6 as the program is just counting the number of times it comes across 'd' and 'e'

Can anyone shed some light on this for me thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 31 2008
Added on Dec 31 2007
14 comments
852 views