Strings are forever
So here’s a thing. They’re immutable, you can’t change them. So trying to change the name from Bob to Percy like this won’t work.
Developing in Android Studio, it just ignores that line and the app compiles. The name remains Bob. Too bad for Percy!
The answer is to assign the result of the replacement to myString and the names are changed.
Strings can be equal
Want to compare two strings? No problem. Use equals(), like this:
This does an exact comparison.
You can also ignore their cases when comparing strings by using equalsIgnoreCase().
Strings can be joined
You can join any number of strings using concat(), like this:
The resulting string contains Peter Smith.
Strings and characters
Converting a String to a char array
You may want to access the individual characters making up the string. One way of doing this is with the char array:
Here are the individual characters and their index in the array:
Use the index to identify the character. For example, you could access the character H like this, myCharArray[0].
Converting a char array to a String
You can also convert a char array to a string like this:
Trim the white spaces
Use trim() to get rid of any white spaces at beginning and end of a string:
Here’s the result:
Doing the splits: Splitting a string
You can split a string at a specific character. This can be useful, for example, in getting data out of a comma-delimited text file.
Simply split the string at the comma. The resulting pieces are stored in a String array.
Here’s the result of splitting the string at the blank space:
Little Strings: Getting sub-strings from strings
There are two ways of doing this.
You can get a sub-string starting at a specific character till the end of the string.
You can also get a sub-string from between two specific characters. Have a look at this example:
This is what the two sub-strings look like:
Up or down: Changing the case of a String
Use toLowerCase() to change the whole string to lower case.
Use toUpperCase() to change the whole string to upper case.
Here’s an example of how to change the first letter of each word to upper case.
We first change the whole string to lower case. Then we split the string to get the two words, Hello and Dolly.
Then we get the first character in each word, change these to upper case and put the words together:
The result:
Getting String values of non-strings
Here’s an example of how to get the string value of an integer variable:
Check the official documents for a lot more on what you can do with strings.
Find out more about the LogCat, which we use quite a lot in these examples, here.
Have a look at the MainActivity.java file in pdf format.