We have the primitive data type string.. so why do we need String
Primitive data types are great because they don't take up much memory. However all they do is store data. What if you want to do more? The String class store a string but it also has many very useful member methods.
Create a string
String str = "abc";
indexOf - Find the position of the first occurence of a given letter ( or word) in the string.
int pos = str.indexOf("b");
pos will be 1.
Note: If the letter or word is not found, the method will return -1.
pos will be 1.
Note: If the letter or word is not found, the method will return -1.
Substring - Retrieve part of a string
Substring will retrieve part of a string. The overload with one parameter will return the substring starting at the position supplied and ending at the end of the string:
String str = new String("The quick brown fox jumps over the lazy dog.");
String strSecondString = str.substring(20);
System.out.println(strSecondString);
Output:
jumps over the lazy dog.
You can pass two parameter variables to the substring method. The string returned will be the part from the first value to the second value -1.
String str = new String("The quick brown fox jumps over the lazy dog.");
String strSecondString = str.substring(20,22);
System.out.println(strSecondString);
Output:
ju
Note: The characters at position 20 and 21 are returned, but not the character at position 22.
String str = new String("The quick brown fox jumps over the lazy dog.");
String strSecondString = str.substring(20);
System.out.println(strSecondString);
Output:
jumps over the lazy dog.
You can pass two parameter variables to the substring method. The string returned will be the part from the first value to the second value -1.
String str = new String("The quick brown fox jumps over the lazy dog.");
String strSecondString = str.substring(20,22);
System.out.println(strSecondString);
Output:
ju
Note: The characters at position 20 and 21 are returned, but not the character at position 22.