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
- Output the length of the String “I never saw a purple cow”
- Convert the String “I never saw a purple cow” to uppercase and output the resulting string.
- Output the String “I never saw a purple cow” as separate words.
- Output the following String array as one String: words [] = {“Calling”, “occupants”, “of”, “interplanetary”, “craft”};
- 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
- 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”
- Prompt the user to enter a string. Output the number of times the letter ‘e’ appears in the string.
- Prompt the user to enter a string. Output the number of vowels in the String.
- 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”
- 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.