5 – String Problems

1 Sample Code

public class StrSamples
{
    public static void main (String args [])
    {
       String s ="This is a sample string";
       System.out.println(s);
       System.out.println("It contains this many characters (counting spaces): "+ s.length());
       System.out.println("Here it is split up by whitespace:");
       String [] seperated= s.split("\\s+");
       for(int i=0; i<seperated.length; i++)
       {
           System.out.println(seperated[i]);
       }
       System.out.println("Here it is split up by the letter a:");
       String [] sep2= s.split("a");
       for(int i=0; i<sep2.length; i++)
       {
           System.out.println(sep2[i]);
       }
       System.out.println("Here are the characters from position 1 to 3:");
       System.out.println(s.substring(1,3));
       System.out.println("Here it is with the spaces removed");
       String r= s.replaceAll("\\s", "");
       System.out.println(r);
       System.out.println("Here it is with the letter s replaced by sausage");
       r= s.replaceAll("s", "sausage");
       System.out.println(r);
       System.out.println("Here it is with the lower case letters turned to *s");
       r= s.replaceAll("[a-z]", "*");
       System.out.println(r);
    }
}

2 Exercises

  1. Output the length of the String “I never saw a purple cow”
  2. Convert the String “I never saw a purple cow” to uppercase and output the resulting string.
  3. Output the String “I never saw a purple cow” as separate words.
  4. Output the following String array as one String: words [] = {“Calling”, “occupants”, “of”, “interplanetary”, “craft”};
  5. Prompt the user to enter a string. Output the string as separate words in alternate upper and lower case: SO it LOOKS like THIS example
  6. Prompt the user to enter a String. Output a String named acronym that contains the initial letters of the words input. Example: input “British Broadcasting Corporation” output “BBC”
  7. Prompt the user to enter a string. Output the number of times the letter ‘e’ appears in the string.
  8. Prompt the user to enter a string. Output the number of vowels in the String.
  9. Prompt the user to enter a String. Output a String with the vowels replaced with *’s. Example: input “I never saw a purple cow” output “* n*v*r s*w * p*rpl* c*w”
  10. A palindrome is a string that reads the same forwards and backwards. Examples are “radar” and “rotavator”. Write a program that accepts a String as input and outputs “Palindrome” if the String is a palindrome, and “Not Palindrome” otherwise.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.