Computer Programming 2 Week 10
Computer Programming 2 Week 10
There's more to strings than meets the eye. Unlike int variables, or double
variables, strings are objects. What this means in practice is that you can
do things with strings of text that you can't do with int or double variables.
(The same applies to the primitive data types boolean, byte, single, char,
float, long and short: they are not objects like strings are.)
This tells Java to set up a string object with the four characters "B", "i", "l"
and another "l".
In the previous week, we had an array which held strings of text. We then
sorted the array:
When the program is run, the output is this:
Start a new project for this, and add the following code:
The first two lines of code just set up a String variable to hold the text "text
to change", and then we print it out. The third line sets of a second String
variable called result. The fourth line is where we do the converting:
result = changeCase.toUpperCase( );
To use a string method you first type the string you want to work on. For
us, this was the string in the variable called changeCase. Type a dot after
the variable name and you'll see a list of available methods that you can
use on your string. Select toUpperCase. (The method needs the empty
round brackets after it.)
After Java has changed the word to uppercase letters, we're storing the
new string into our result variable.
When the program is run, the Output window displays the following:
But you don't have to store the converted word in a new variable. This
would work just as well:
System.out.println( changeCase.toUpperCase( ) );
Here, Java will just get on with converting the string, without needing to
assign the result to a new variable.
Comparing Strings
You can compare one string to another. (When comparing, Java will use
the hexadecimal values rather than the letters themselves.) For example,
if you wanted to compare the word "Ape" with the word "App" to see which
should come first, you can use an inbuilt string method called compareTo.
Let's see how it works.
You don't need to start a new project for this: simply comment out (or
delete) the code you already have. Now add the following code:
We've set up two string variables to contain the words "Ape" and "App".
The compareTo method is then this line in the code above:
result = Word1.compareTo( Word2 );
The compareTo method returns a value. The value that is returned will
be greater than 0, less than 0, or have a value of zero. If Word1 comes
before Word2, then the value that is returned will be less than 0. If Word1
comes after Word2 then the value returned will be greater than 0. If the
two words are identical then a value of 0 will be returned.
However, when you compare one string of text with another, Java
compares the underlying hexadecimals values, rather than the actual
letters. Because uppercase letters have a lower hexadecimal value than
lowercase ones, an uppercase letter "A" in "App" will come before a
lowercase letter "a" in "ape". Try it for yourself. Change "Ape" to "ape" in
your code. The Output will read "Word1 is more than Word2", meaning
that Java will place the word "ape" after the word "app" alphabetically.
Video Tutorial (compareTo):
https://www.youtube.com/watch?v=iTC43mLZG38
You first type a string name, language in this case. Type a dot after the
string name, then add concat. In between the round brackets of concat,
enter the text you want to add to the end of the string.
You can chain the concat method. Here's an example that uses concat
to construct a name in the format "Personal Name, comma, Family
Name":
String personalName = "Kenny";
String familyName = "Carney";
String fullName = "";
fullName = fullName.concat(familyName).concat(",
").concat(personalName);
System.out.println(fullName); //prints Carney, Kenny
The above code uses concat three times. The string we want to build is
the fullName string, which starts out empty. We then add the family
name, then a comma, then the personalName.
concatResult = concatResult.concat(padWithA);
System.out.println(concatResult);
//Prints: AAAAA
Again, you can either delete or comment out the code you already have.
But here's the new code to try:
The string you're trying to search comes first. After a dot, type indexOf. In
between the round brackets of indexOf, you have several options. One of
the options is to type a single character (or the name of char variable).
We've placed our ampersand variable between the round brackets of
indexOf. Java will then tell us the position of the @ character in the email
address. It will store the value in the result variable.
When you run the code, the output will be 4. You might think that the @
sign is the fifth character in the email address. But indexOf starts counting
at 0.
However, if the character is not in the word that you're searching, indexOf
will return a value of -1. To test this out, delete the @ sign from your
email_address string. Then run your code again. You'll see -1 as the
output.
You can use the return value of -1 to your advantage. Here's the code
again, only with an IF statement that examines the value of the result
variable:
So if the result of indexOf is -1 then we can do one thing, else allow the
user to continue.
You can also use indexOf to test for more than one character. The code
below checks the email address to see if it ends with ".com":
The code is almost identical, except we're now using a String variable to
hold the text we want to check for (.com), and not a char variable.
Again, a result of -1 will be returned if the text to search for is not found
in the String that comes before the dot of indexOf. Otherwise, indexOf will
return the position of the first of the matching character. In the code above,
the dot is the seventh character of the email address, when you start
counting from 0.
You can also specify a starting position for your searches. In our email
address example, we can start searching for the ".com" after the @ symbol.
Here's some code that first locates the position of the @ symbol, and then
uses that as the start position to search for ".com".
The new line of code is this one:
The only thing different is the addition of an extra variable between the
brackets of indexOf. We still have the string we want to search for (which
is whatever text is in the dotcom variable), but we now have a starting
position for the search. This is the value of the variable called atPos. We
get the atPos value by using indexOf to locate the position of the @ symbol
in the email address. Java will then start the search from this position,
rather than starting at 0, which is the default.
Ends With … Starts With
For the programme above, you can also use the inbuilt method endsWith:
Boolean ending = email_address.endsWith( dotcom );
You need to set up a Boolean variable for endsWith, because the method
returns an answer of true or false. The string you're trying to test goes
between the round brackets of endsWith, and the text you're searching
goes before it. If the text is in the search string then a value of true is
returned, else it will be false. You can add an if … else statement to check
the value:
if (ending == false ) {
System.out.println( "Invalid Email Address" );
}
else {
System.out.println( "Email Address OK " );
}
Substring
One really useful method available to you is called substring. This method
allows you to grab one chunk of text from another. In our email address
program above, for example, we could grab the last five characters from
the address and see if it is co.uk.
To get some practice with substring, we'll write a small Name Swapper
game. For this game, we want to change the first two letters of a family
name and swap them with the first two letters of a personal name, and
vice versa. So if we have this name:
"Bill Gates"
we would swap the "Ga" of "Gates" with the "Bi" of "Bill" to make "Bites".
The "Bi" of "Bill" will then be swapped with the "Ga" of "Gates" to make
"Gall". The new name printed out would be: "Gall Bites"
We'll use substring for most of this programme. Substring works like this:
FirstNameChars = FullName.substring( 0, 2 );
You set up a string to search, in this case the string "Bill Gates". The string
you're trying to search goes after an equals sign. After a dot, type the name
of the method, substring. There are two ways to use substring, and the
difference is in the numbers between the round brackets. We have two
numbers in the code above, 0 and 2. This means start grabbing characters
at position 0 in the string, and stop grabbing when you have two of them.
The two characters are then returned and placed in the variable
FirstNameChars. If you always want to go right to the end of the string,
you can just do this:
String test = FullName.substring( 2 );
When the program runs, the Output window should look like this:
So the substring method has allowed us to grab the first two characters of
the name "Bill".
To get the first characters, we had a 0 and a 2 between the round brackets
of substring. You might think that to get the "Ga" of "Gates" that we could
just do this:
= FullName.substring(5, 2);
We still want two characters, after all. Only this time, the 5 would tell Java
to start from the "G" of "Gates". (The first position in a string is position 0
not position 1.) So, start at position 5 in the string and grab 2 characters.
However, running that code would get you an error. That's because the
second number between the round brackets of substring doesn't mean
how many characters you want to grab. It means the position in the string
that you want to end at. By specifying 2 we're telling Java to end at the
character in position 2 of the string. As you can't go from position 6
backwards to position 2 you get an error instead.
(NOTE: If you start the count at 0 in the string "Bill", you might think that
position 2 is the letter "l". And you'd be right. But substring starts before
the character at that position, not after it.)
To get the "Ga" of "Gates", therefore, you could do this:
FullName.substring( 5, FullName.length( ) - 3 );
The second number is now the length of the string minus 3 characters.
The length of a string is how many characters it has. "Bill Gates" has 10
characters, including the space. Take away 3 and you have 7. So we're
telling substring to start at character 5 and end at character 7.
And that would work perfectly well for people called "Bill Gates". But the
programme wouldn't work if you name was, say, "Billy Gates". The code
above would then grab the space character plus the letter "G", which is
not what we want at all. We want the programme to work whichever two
names are entered. So we have to get a bit clever.
One thing we can do is to note the position of the space in the two names.
The 2 characters we want to grab from the second name always come right
after the space character. We want some code that grabs those first two
characters after the space.
To specify a space character you can type a space between two double
quotes (or single quotes). This then goes between the round brackets of
indexOf. The value returned will be an integer, and it is the position of the
first occurrence of the space character in the string FullName.
Test it out by adding the line above to your code: Add a print line to check
the Output:
Run the programme to see the following Output:
So the space is at position 4 in the string. We can use this fact to grab the
first two characters of "Gates", or indeed any second name. We tell Java to
go from the first character after the space, and end at the next two
characters:
FullName.substring( spacePos + 1, (spacePos + 1) + 2)
So the two numbers between the round brackets of substring are these:
spacePos + 1, (spacePos + 1) + 2
We want to start at the first character after the space (space + 1), and end
two characters after this position, which is (spacePos + 1) + 2.
Add the following lines to your code (The ones highlighted. Our new
substring method spills over on to two lines, but you can keep your on
one, if you prefer):
Again, we can use substring to get the remaining characters from the first
name:
String OtherFirstChars = "";
OtherFirstChars = FullName.substring( 2, spacePos );
System.out.println( OtherFirstChars );
System.out.println( OtherSurNameChars );
Not the numbers in between the round brackets of substring. To get the
other first name characters, the numbers are these:
2, spacePos
This tells Java to start at position 2, and go right up to the position of the
space. To get the rest of the second name, however, it's a little bit trickier:
(spacePos + 1) + 2, FullName.length( )
We now have all the parts of the name. To join them together, we can use
concatenation:
Add the new lines to your own code. When you run your program, the
Output window should display the following:
We can get rid of the print lines, though, and invite a user to enter a first
name and second name. Here's the new program (the only addition is for
the keyboard input, which you've used before):
The Output window should look something like this, when you run your
program and enter a first name and surname:
We should, of course, add some error checking. But we'll assume the
user can enter a first name and surname with a space between the two.
If not, the program will crash!
Video Tutorial:
https://www.youtube.com/watch?v=US4v4SD0iiU
Activity:
Write a Java program to replace each substring of a given string that
matches the given regular expression with the given replacement.
Sample String: "The quick brown fox jumps over the lazy dog."
// In the above string replace all the fox with cat.
Sample Output:
Original string: The quick brown fox jumps over the lazy dog.
New String: The quick brown cat jumps over the lazy dog.