The String class is used for text manipulation. As you read, you will learn different ways to create Strings, methods to manipulate Strings, the String concatenation operator '+', and about how Strings are immutable.
18. Substrings
Answer:
if ( line.length() > colNum &&
line.charAt( colNum ) != ' ' )
System.out.println( counter + ":\t" + line );
The short-circuit operation of &&
means that line.length() > colNum
is tested first.
If this result is false, then the next part of the condition is not tested (since the result of AND will be false
regardless of its result). So line.charAt( colNum )
is only performed when it is certain that the line contains a character at index colNum.
Substrings
Substrings
A substring of a string is a sequence of characters from the original string. The characters are in the same order as in the original string and no characters are skipped. For example, the following are all substrings of the string "applecart":
apple cart pple e lecar
You have previously seen (in chapter 11) the substring()
method of String
objects:
public String substring(int beginIndex )
This method creates a new substring that consists of the characters from character number beginIndex
to the end of the string. For example
"applecart".substring(5)
contains the characters "cart" .
Remember: character numbering starts with zero. The leftmost character of a string is character zero. The rightmost character is character
length-1
.
Question 18:
What is printed by the following code:
String source = "applecart"; String sub = source.substring(6); System.out.println( sub ); System.out.println( source );