Logout

String Processing

String Processing Important Methods:

Here are the three main String methods you'll need for today:

indexOf - returns the index (an int) of a certain character or substring of characters in your String. Remember that index numbering starts at zero. Here's an example:

    String s = "hello world";
    System.out.println(s.indexOf(llo world));
Would output: 2, since in the string "hello world", "llo world" starts at index 2.

With indexOf, we could also locate the index of a single character if we wanted, and this is often how we will use indexOf - for a character rather than a substring. So:

    String s1 = "sun and moon";
    System.out.println(s1.indexOf(m));
Would output: 8, since in the string "sun and moon", "m" is at index 8.




substring - returns a substring from your string. If just one parameter is sent, then it's the substring from that index to the end. If two parameters are sent, then it's the substring from the index of the first parameter to the one before the second parameter. Here are a couple of examples:

    String s2 = "How are you doing?";
    System.out.println(s2.substring(8));
Would output: you doing?, since starting at index 8, you doing? are the remaining characters of the string.

    String s3 = "Fine, thanks for asking."
    System.out.println(s3.substring(8, 12));
Would output: "hank", since from the index 8 to the index 11, are the chars h a n k.




toUpperCase - returns the string back as all upper case characters. So if this section were String s, s.toUpperCase would return: TOUPPERCASE - RETURNS THE STRING BACK AS ALL UPPER CASE CHARACTERS.

length- returns the length of a string based on normal counting starting with one, not zero.


charAt - returns the characater with the index which you send as a parameter.

String s4 = "Another string of characters.";
Sysetme.out.println(sr.charAt(3));

Woudl output: "t", since that's the letter at the 3rd index of the string. (Remember that element numbering starts with 0.)

 

With just this small portion of the full repertoire of String methods, we can do quite a bit. Look at your homework for examples, like methods which print out characters of a string backwards, or that capitalize every second letter.

And at this point, you will want to start looking to the Morelli textbook "Java, Java, Java" to get a deeper understanding and more examples of what you find in these "Java Revolution" notes. The String chapter begins on page 305.