Revisiting Strings#
We've talked about Strings before, they are a way to store text in a variable. But Strings also offer a few very interesting things besides storing the letters.
Are We There, Yet?!#
Sometimes you need to know how "long" your string is - how many characters of text there are. We need to be able to do this, because the text might be an input from a user, perhaps their name, and we can't correctly predict how long that is going to be.
Functions and Methods
If that looks like calling a function, then your instinct is very good! This is totally calling a function! When functions belong to an object, we call them "methods", but don't worry about the distinction right now.
Methods vs. Properties
One thing that really drives me nuts here, is how Array.length
is a property (it has no parentheses) and String.length()
is a method (we're calling a function, it has these parentheses). Sadly, I can't change that part of programming, I can just point out to you that there may be things like these that are very easy to confuse. Sorry.
Comparing Two Strings#
When we introduced conditions, I already included this bit of information: Checking for equality in strings works a little differently. Whenever we compare two strings for equality, we can't use ==
for the job. You hopefully remember that you can write firstVariable.equals(secondVariable)
.
What if we want to know a little bit more than just that? What if we needed to compare them for sorting? There are two functions .compareTo()
and .compareToIgnoreCase()
like their names suggest, one of these will ignore the "case" — if letters are capital or miniscule. Both comparisons will return a number and it can be either negative, 0 or positive depending on if the left string comes first, if they are equal or if the right string comes first lexicographically. This will probably be easier to explain directly in code form:
String word1 = "dog";
String word2 = "elemental hydrogen";
int result = word1.compareTo(word2);
println(word1 + " compared to " + word2 + " results in " + result);
if (result == 0) {
println("both are equal");
} else if (result < 0) {
println(word1 + " would come first in a dictionary");
} else {
println(word2 + " would come first in a dictionary");
}
Try a few other words
change word1
and word2
to see a few different results.
Let's try that with the same word but ignoring the case:
String word1 = "DoG";
String word2 = "dog";
int result = word1.compareToIgnoreCase(word2);
println(word1 + " compared to " + word2 + " (ignoring case) results in " + result);
// this will print "DoG compared to dog (ignoring case) results in 0"
// if we ignore uppercase and lowercase, these two are indeed equal.
Individual Characters#
If you have a String, you might want to take a look at its individual characters. We can ask Processing to give us a single character out of a whole string, and — you guessed it — we start counting at zero!
So, .charAt()
can give us a single letter from a string, and all we need is an index.
Let's combine this with .length()
to iterate through all of our letters!
The kicker here are lines 15 (loop) and 16 (getting the single letter), the rest is just "where do I even draw this" (x
and y
coordinates).
Searching in Strings#
Does something come up in this text? Might be a question you could have. And .contains()
can give you a boolean answer to that question!
String text = "When I grow up, I want to be a homeowner.";
if (text.contains("meow")) {
println("found it!");
} else {
println("no meows found");
}
What does this code print?
It prints "found it!" because the letters "meow" are contained in "homeowner". This fact will now live rent-free in your brain. You're welcome.
If you ever need to find where in your string something exists, you can use .indexOf()
, which you can use like this:
// text taken from https://en.wikipedia.org/wiki/Darmstadt with slight alterations
String description = "Darmstadt is a city in the state of Hesse in Germany, located in the southern part of the Rhine-Main-Area (Frankfurt Metropolitan Region). Darmstadt has around 160,000 inhabitants.";
int index = description.indexOf("city");
println("city appears at index " + index);
// this prints "city appears at index 15"
So, .indexOf()
takes a search string as parameter, and returns a number (again, 0-based) which we could use later on. But what if we never actually find the thing we're looking for?
continuation! we're assuming the String from above! | |
---|---|
This would print -1
– "but where is -1
?!" I hear you ask! – nowhere! There is not a single q
in the text above! So our .indexOf()
can't find one. And so it reports back -1
- this is what we call a "sentinel value" - a special return value that has some pre-defined meaning. -1
means "I did not find what you were looking for".
Replacing Text#
String original = "Hello, this is Diana Prince!";
String result = original.replaceAll("Diana Prince", "Wonder Woman");
println(result);
This will print the line "Hello, this is Wonder Woman!". .replaceAll()
takes all occurrences of "Diana Prince" and replace them in the result
. Replace takes something it searches for1 and something to replace it with as its two parameters.
Splitting and Combining#
String list = "Milk, Bread, Vegetables, Rice, Toilet Paper, Toothpaste";
String[] items = list.split(", ");
for (String item : items) {
println("* " + item);
}
.split()
takes a search string as its parameter and will split your text into individual shorter Strings which are returned as an Array. This is extremely useful if you have simple data that you can split by a known character (often a ,
comma or a ;
semi-colon). The opposite of that is String.join()
— please note that this is called differently, .split
is called with an existing string that will be split up (list.split()
), but String.join()
does not have a string, it produces one, so we're actually writing String.join()
.
String[] members = {
"Jin",
"Suga",
"J-Hope",
"RM",
"Jimin",
"V",
"Jungkook"
};
String result = String.join("+", members);
println(result);
The reference for String has many many more methods. Looking over the long list called "method summary" may give you further ideas what you would like to try. The methods I highlighted above will get you very far already. This is probably 80% of what I use from all the possibilities that String
offers.
-
.replaceAll()
actually takes a "regular expression" as its first parameter, which is a whole language to learn in and of itself. It's very powerful, but it would go way beyond the scope of this short collection. If you're bored with this, take a look at regular expressions. They can be fun. ↩