In these notes you will learn:
In Processing, a string is a sequence of 0 or more characters. For example, these are all strings:
"mouse"
"I'm sorry Dave, I'm afraid I can't do that"
"X"
"1\ntwo\tthree"
"\\n is the newline character"
""
More precisely, these are string literals because they begin and end with a " (a double-quote)
Notice the last example above. The string "" is known as the empty string: it is the (unique) string with 0 characters in it.
Sometimes we want to add formatting to our string. For example, if you’re printing the contents of a book to the screen using one (very large) string, you might want to start a new line quite often. To achieve this we use escape characters, such as \n and \t. The most common escape character is probably \n, and it is used to represent a newline character. This character tells the computer that when displaying this text, it should start a new line after the newline character. For example, typing the following in a processing program println(1\ntwo\nthree) results in the following being printed to the console:
1
two
three
What if we want to place " or \ in our string? If we were to write "He said "Hello" to me", we would get an error because to Processing this looks like we want the string "He said " followed by... what? For that we use \. For example, println(\\n is a new line character) gives \n is a new line character because we’ve escaped the newline character. In this way we may use double-quotes and backslashes in strings: println("He said \"Hello\" to me. To do a \\, you escape it with \\\\") will result in He said "Hello" to me. To do a \, you escape it with \\
We also refer to variables of type String as being strings. For example:
String greeting = "Hello there!";
println(greeting);
Recall that the println function prints a string on the console: the small black window at the bottom of the editor window.
Note
In Processing println can be extremely useful when debugging your program. You can use to print the value of a variable, or other helpful messages.
String is another example of a type. Declaring a variable to be of type String ensures that Processing will only allow it to store string. For instance, the following will produce an error:
String s = "apple";
s = 55; error: cannot convert from int to String
Notice also that String begins with a capital S. If you wrote string instead, Processing wouldn’t recognize it.
Processing provides numerous special functions for dealing with strings. For now we will focus only on a few of the most useful ones.
It is often useful to know how many characters a string has. In processing, every String object has .length() function. Notice the . before the function. We use like this:
String fruit = "lemon or apple";
println(fruit.length()); // prints 14
If you run this, you will see that 14 is printed to the console, because there are exactly 14 characters in in the string lemon or appale. Notice that spaces (" ") count as characters.
In general, if str is a String, then str.length() returns the number of characters in str. This is an example of function that belongs to an object. We will see other functions belonging to String, and later we will see other objects. To get at the function func() belonging to object obj, we will always use obj.func(). We call . the dot operator. It is always used when we want to access the properties of an object. More on this later in the course.
We don’t have to store our string in a variable to access the length() function, although usually we do:
println("Main Window".length()); // prints 11
Remember to treat strings that contain escape characters with suspicion. An escape character counts as one character, even though it written with more than one symbol:
String s1 = "\n";
println(s1.length()); // prints 1.
String s2 = "Hello\tThere";
println(s2.length()); // prints 11.
The string "Hello\tThere" contains exactly 11 characters (not 12!): Hello, \t and There.
Earlier we discussed the empty string. The length of the empty string is 0:
String s = "";
println(s.length()); // prints 0.
Warning
Don’t confuse the empty string with a string that contains a space:
String s = " ";
println(s.length()); // prints 1
Sometimes you need to know if two string variables, say s and t are equal. By equal, we mean that they have the same characters in the same order. So far, when we wanted to test whether two values are equal, we used the == boolean operator. However for strings that is problematic. The trouble is that == is used to compare primitive types, and Strings are not primitive. When Processing does str1 == str2, it checks to see if the memory address for str1 is the same as the memory address for str2. If that is the case, we get true. While it’s certainly the case here str1 is equal to str2, there may be situations where str1 and str2 have the same characters in the same order, but reside in different locations in memory.
So, to compare strings we use the .equals() function:
if (s.equals(t)) {
println("s and t are the same");
} else {
println("s and t are different");
}
Finally, note that string comparisons are case-sensitive. That is “apples” and “Apples” are not equal strings.
Processing lets you easily create new strings by adding two ore more strings together. This is known as string concatenation. For example:
String firstName = "Donald ";
String lastName = "Knuth";
String fullName = firstName + lastName; // "Donald Knuth"
Adding strings together is one way to create formatted output:
String name = "R.A. Dickey";
println("Hello " + name + "! How are you today?");
// prints "Hello R.A. Dickey! How are you today?"
It’s also possible to concatenate primitive values with Strings (as we’ve already seen). Here, Processing automatically converts the primitive type to a string, before performing the concatenation:
String muppet = "Swedish";
muppet += " Chef"; // Swedish Chef
Processing also has a data type char. This is a primitive data type that is used to represent a single character. In Processing we use single quotes to denote characters. For example, these are all characters, also known as character literals:
'A' 'a' '7' '=' '\'' '\n'
Unlike with strings, there is no such thing as an empty character. That is, writing '' is an error.
While characters might look like strings, they are not: 'a' and "a" are completely different types, and so you can’t compare them!
Since chars are primitive, we use the == operator to compare them to one another:
char a = 'q'
char b = 'Q'
if (a == b) {
println("Same");
} else {
println("Different");
}
Finally, we can access individual characters of a given string, by using the charAt() function (note: this is a String function! chars don’t have functions.). For instance:
String s = "apple";
char firstChar = s.chartAt(0); // 'a'
char secondChar = s.cartAt(1); // 'p'
char thirdChar = s.charAt(2); // 'p'
The number that we pass to charAt() as a parameter is the index of the character we would like to get. Notice that indices for Strings start at 0, and not one: the first character is indexed at 0, while the last character is at s.length() - 1. A good way to remember this, is that when we’re asking for charAt(i) for some i, we are asking for the character that is i characters after the first character. Hence, charAt(0) is the character that is 0 characters away from the first character — it is the first character itself.
There is a lot more that we could say characters (and strings). However, we won’t be using characters much in this course. Strings of length 1 will work well most of the time.
What is a string?
What is the empty string?
Where does println(s) print s?
What is the newline character?
What does println("1\n2\n3") print?
How do you determine the length of a string s?
How do you test if the strings s and t are the same (i.e. they have the same characters in the same order)?
Why is comparing strings with == a problem?
What is string concatenation?
What is the value of the expression "1" + "2"?
What is the value of the expression "1" + 2?
Give an example of how the += operator works with strings.
Explain the difference between 'a' and "a".
How would you test if the characters (both of type char) x and y are equal?
Notice what happens if we run println('a' == 97): for one, Processing lets us do it with no complaint. For another, it thinks that the letter ‘a’ is equal 97!
Why do we get true?
In general, why does it make sense to compare a character to an int?
Write a program that makes a ball bounce around the screen and modify it so that every time you click on the screen with the mouse, this message is immediately printed on the console window:
mouse click at (x, y)
Replace x and y with the coordinates of where the mouse pointer actually was when it was clicked.
Make sure the console message is exactly the same format as in the example!