What is a String?
The String object allows you to store text ( e.g. "hello"). That is a number of letters together.
The String class includes many useful member methods which allow you to convert or interrogate the stored text. |
Creating a String
To create a String specify the data type, a name and a value:
String greeting "hello";
String greeting "hello";
Find the length of the String
int len = greeting.length();
Convert all letters to Upper or Lower Case
String upper = greeting.toUpperCase();
String lower = greeting.toLowerCase();
This is a good trick if you want to compare non case sensitive user input.
String lower = greeting.toLowerCase();
This is a good trick if you want to compare non case sensitive user input.
Check if Two Strings contain the same word
There are two methods to compare two two strings: Equals and CompareTo.
The Equals Method
The Equals methods will return true if both strings are the same. Otherwise it will return false.
WordOne = "tiger"
WordTwo = "lion"
if( WordOne.equals( WordTwo))
{
// words are the same
}
else
{
// words are not the same
}
WordOne = "tiger"
WordTwo = "lion"
if( WordOne.equals( WordTwo))
{
// words are the same
}
else
{
// words are not the same
}
The CompareTo Method
The CompareTo method will return 0 if the strings are the same. But it will also let you know which word is earlier in the alphabet ( by subtracting the ASCii value of the first letter of the second word from that of the first).
In the example below zebra is later in the alphabet than chimp so the value returned will be positive ( 23 which is the Ascii value of "z" minus the Ascii value of "c").
String animalOne = "zebra";
String animalTwo = "chimp";
System.out.println(animalOne.compareTo(animalTwo));
// will display 23.
In the example below zebra is later in the alphabet than chimp so the value returned will be positive ( 23 which is the Ascii value of "z" minus the Ascii value of "c").
String animalOne = "zebra";
String animalTwo = "chimp";
System.out.println(animalOne.compareTo(animalTwo));
// will display 23.
Find a String within a String
Use IndexOf to find the starting index position of one string ( or character) within a string. A String stores an array of chars, so the first position will be zero.
int pos = greeting.indexOf("h");
// stores 0 in pos as "h" is the first letter in the string. int pos = greeting.indexOf("ello"); // stores 1 in pos as "ello" starts at position 1. int pos = greeting.indexOf("l"); // stores 2 in pos as this is the position of the first "l" in the string. |