JavaBat Java help pages:
| If and Boolean | Java Strings | While and For Loops | Arrays and Loops |
The Java String object contains a sequence char values (pronounced "car"). A char represents a single character, such as 'a' or 'Z' or 'µ' or '∑'. A char value is written in Java code using single quotes (') as shown here. Java supports the unicode character set, so we are no limited to just roman A-Z characters. The char type is a simple primitive type, very similar to int, so use simple = to copy char values, and == and != to compare char values. Rather than dealing with individual characters, you mostly deal with sequences of characters stored in a Java String object.
A string holds a sequence of characters, such as the string "Hello" or the string "It was the best of times. It was the worst of times.". A string can store a single word or the text of an entire book. Java's built in String class has many powerful and convenient features to operate on string data. Each String object stores a sequence of chars, such as "Hello", and implements methods that operate on those chars. We can create a String object the usual way with the "new" operator:
String str = new String("Hello");
Strings are so common in Java code that there is a special syntax to create them. You can create a String object simply by writing the desired text within double quotes "like this". The shorter version of the code below creates a new String object exactly as above.
String str = "Hello";
It's valid to create a string made of zero characters -- the quotes are right next to each other with nothing in between. This is known as the "empty string".
String empty = ""; // creates an empty string (zero chars)The empty string is a valid string object, and the many of the operations described below work correctly on the empty string where it makes sense.
String start = "Hi"; String end = "coffee time!"; String result = start + " it's " + end; // result is "Hi it's coffee time!"In computer science, the verb "concatenate" is used for this situation -- appending sequences together to make one big sequence. This special feature of the + operator also works when a string is combined with a primitive such as an int or double or char. The int or double value is automatically converted to string form, and then the strings are appended together. This feature of the + is very a convenient way to mix int and double values into a string:
int donutCount = 123; char end = '!'; String result = "I ate " + donutCount + " donuts" + end; // "I ate 123 donuts!"
int length() -- length() returns the number of chars in the receiver string. The empty string "" returns a length of 0.
String a = "Hello"; int len = a.length(); // len is 5
String toLowerCase() -- toLowerCase() returns a new string which is a lowercase copy of the receiver string. Does not change the receiver.
String a = "Hello"; String b = a.toLowerCase(); // b is "hello"
String toUpperCase() -- toUpperCase() is like toLowerCase(), but returns an all uppercase copy of the receiver string. Does not change the receiver.
String a = "Hello" String b = a.toUpperCase(); // b is "HELLO"
String trim() -- trim() returns a copy of the receiver but with whitespace chars (like space, tab, newline) removed from the start and end of the String. Does not remove whitespace everywhere, just at the ends. Does not change the receiver.
String a = " Hello There "; String b = a.trim(); // b is "Hello There"
String word = " hello "; word.trim(); // ERROR, this does not change word // word is still " hello ";When calling trim() (or any other string method) we must use the result returned by the method, assigning into a new variable with = for example:
String word = " hello "; String trimmed = word.trim(); // Ok, trimmed is "hello"If we do not care about keeping the old value of the string, we can use = to assign the new value right into the old variable:
String word = " hello "; word = word.trim(); // Ok, word is "hello" (after the assignment)This works fine. The trim() method returns a new string ("hello") and we store it into our variable, forgetting about the old string.
String a = "hello";
String b = "there";
// Correct -- use the .equals() method
if (a.equals("hello")) {
System.out.println("a is \"hello\"");
}
// NO NO NO -- do not use == with Strings
if (a == "hello") {
System.out.println("oops");
}
// a.equals(b) -> false
// b.equals("there") -> true
// b.equals("There") -> false
// b.equalsIgnoreCase("THERE") -> true
There is a variant of equals() called equalsIgnoreCase() that compares two strings, ignoring uppercase/lowercase differences. If you want to ignore uppercase/lowercase differences in your application, another solution is to covert all strings to, say, lowercase with toLowerCase() when they come into the system.
String also includes the handy startsWith()/endsWith() methods that test if one string matches the start or end of another:
String str = "hello";
str.endsWith("llo") -> true
str.startsWith("he") -> true
str.startsWith("hx") -> false
str.startsWith("") -> true (note, empty string is true)
String a = "apple";
a.compareTo("zebra") → -1
a.compareTo("apple") → 0
a.compareTo("aaa") → +1
The example shows a return values of -1/+1. However, in reality, compareTo() can returns a more complex int value reflecting the first char where the strings differ, but the sign of the returned int will be -1/0/+1 as shown here.
There is also a compareToIgnoreCase() comparison method that ignores uppercase/lowercase differences.
String str = "Hello";
This "zero based" indexing style is very common in computer science for identifying elements in a collection. The method charAt(int index) returns an individual char from inside a string (see also the substring() method below). The valid index numbers are in the range 0..length-1. Using an index number outside of that range will raise a runtime exception and stop the program at that point.
String string = "hello"; char a = string.charAt(0); // a is 'h' char b = string.charAt(4); // b is 'o' char c = string.charAt(string.length() - 1); // same as above line char d = string.charAt(99); // ERROR, index out of bounds
String string = "hello"; String a = string.substring(2); // a is "llo" String b = string.substring(3); // b is "lo"The more complex
substring(int start, int end) method takes both start and end index numbers, returning a string of the chars between start and one before end:
String string = "Hello"; String a = string.substring(2, 4); // a is "ll" (not "llo") String b = string.substring(0, 3); // b is "Hel"Remember that substring() goes up to but does not include the end index. The length of the result is (end - start). It's easy to make off-by-one errors with index numbers in any algorithm. Make a little drawing of a sample string with its index numbers to get your code exactly right.
int indexOf(String target) -- searches for the target string in the receiver. Returns the index where the target is found, or -1 if not found.
String string = "Here there everywhere";
int a = string.indexOf("there"); // a is 5
int b = string.indexOf("er"); // b is 1
int c = string.indexOf("eR"); // c is -1, "eR" is not found
int indexOf(String target, int fromIndex) -- this indexOf() searches left-to-right for the target as usual, but starts the search at the given fromIndex (see code example below). The fromIndex does not actually need to be valid. If it is negative, the search happens from the start of the string. If the fromIndex is greater than the string length, then -1 will be returned. Here is an example that calls indexOf() in a loop to find all the "OOP" in string -- note how the fromIndex is used to iterate over the whole string:
void findOOP(String str) {
int start = 0;
while (true) {
int found = str.indexOf("OOP", start);
if (found == -1) break;
System.out.println("Found OOP at:" + found);
start = found + 2; // move start up for next iteration
}
}
int lastIndexof(String target) -- lastIndexOf() does the search right-left starting at the end of the receiver string
int lastIndexof(String target, int fromIndex) -- this lastIndexOf() does the search starting at the given index and working towards 0 (leftwards) in the receiver string
int indexOf(char ch) -- indexOf() version that searches for a single target char instead of a target string.
Suppose we have a string that contains some text with a pair parenthesis somewhere inside of it, like this: "It was hot (darn hot!) I'm telling you". Suppose we want to fix the string so that the part in parenthesis is in all upper case. We can use two calls to indexOf() to find the '(' and ')', and substring to extract the text. Example code:
String string = "It was hot (so hot!) I'm telling you.";
int left = string.indexOf("(");
int right = string.indexOf(")");
// pull out the text inside the parens
String sub = string.substring(left+1, right); // sub is "so hot!"
sub = sub.toUpperCase(); // sub is "SO HOT!"
// Put together a new string
String result =
string.substring(0, left+1) + // It was hot (
sub + // SO HOT!
string.substring(right); // ) I'm telling you.
// result is "It was hot (SO HOT!) I'm telling you."
public String repeat(String string, int count) {
String result = "";
for (int i=0; i<count; i++) {
result = result + string;
}
return result;
}
public String countExclaim(String string) {
int count = 0;
for (int i=0; i<string.length(); i++) {
if (string.charAt(i) == '!') count++;
}
return count;
}
public String oopPair(String string) {
int start = string.indexOf("OOP");
int end = string.lastIndexOf("OOP");
return string.substring(start+1, end);
}
public void printNames(String string) {
int i = 0;
while (true) {
int found = string.indexOf("name:", i);
if (found == -1) break;
int start = found + 5; // start of actual name
int end = string.indexOf(":", start);
System.out.println(string.substring(start, end));
i = end + 1; // advance i to start the next iteration
}
}
javabat.com java learning. Copyright 2006 Nick Parlante.