Home
Site Map
Useful Tools
Graphing Calc

Scientific Calculator

How To Loop Through a String

Loop Through a String


String myString = "abcd";
myString.length(); // holds a value of 4
What will the code below output?

    String myString = "abcd";
        for(int i = 0; i< myString.length(); i++)
            {
               String myLetter = myString.substring(i,i+1);
               System.out.print(myLetter + "\n");
             }
        

Projects for my Computer Science Students

  • 1) Rewrite the loop up above so that you print out the letters in reverse order. This program must be able to reverse the order of myString no matter what the variable is initialized to
    • myString = "abcd" then print dcba
    • myString = "food" then print out doof
    • myString = "hello world" then print out dlrow olleh
  • Run the code below to help you with the Javabat problems below
    String myString= "acatisacatisnotadog";
    		for(int i = 0;i < myString.length()-3; i++){
    			String sub= myString.substring(i,i+3);
    			 System.out.println(sub);
    			
    		}
    

String Loop Assignments

  • assignment 1): write a loop that calculates and then prints out how many times the letter 'c' appears in the String myString below. Your program should work regardless of what myString is initialized to.( Hints: #1. You'll need to loop through myString #2 remember how you had we declared variables in the factorial assignment so that the variables could be remembered outside the loop)
    String myString= "acatisacatisnotadog";
    
    
  • assignment 2) Repeat #1) but this time, print out the number of occurrences of 'ca' in the entire String.
  • assignment 3) Javabat CatDog (Do not do this project in BlueJ. Use Javabat's online compiler.)
    Hint: here's some code to start you off :
    	String myString ="catisadogisacat";
    	for(int i = myString.length();i >=0; i-- )
    		{
    		String sliceOfString = myString.substring(i);
    		System.out.println(sliceOfString);
    		}
    
  • assignment 4) Count Hi
  • assignment 5)XYZ there
  • assignment 6)xy Balance
  • assignment 7) prefix again
?php include $incl. "body_footer.php"; ?> Sitemap