Working with String Methods
String algorithms are built from a few
String methods: length, substring, indexOf, equals, and compareTo. This lesson takes one file name apart with them.String file = "report_final.pdf";
The characters sit at positions 0 through 15, so
file.length() is 16. The last position is always one less than the length.Substrings
file.substring(7, 12) is "final". The first argument is the position where the substring starts, and that character is included. The second is the position where it stops, and that character is left out. So the result holds positions 7 through 11, and its length is 12 minus 7, or 5.With one argument, the substring runs to the end:
file.substring(13) is "pdf". One character on its own is a substring of length 1, so the character at position 0 is file.substring(0, 1), which is "r".A substring is a new string with its own positions. In
String name = file.substring(7, 12); the f that was at position 7 of file is at position 0 of name, and file itself doesn't change.So
file.substring(10, 20) throws an exception, since the string has no position 20.Searching with indexOf
file.indexOf(".") is 12, the position where the period starts. When the text occurs more than once, indexOf reports the leftmost occurrence, and when it doesn't occur at all, it reports -1. So file.indexOf(".txt") is -1, and a test for whether a string contains some text is written as file.indexOf(".txt") >= 0.The two methods work together. With
int dot = file.indexOf(".");, the name before the period is file.substring(0, dot), which is "report_final", since the stopping position is left out. The extension after it is file.substring(dot + 1), which is "pdf". The + 1 steps over the period.Comparing strings
equals reports whether two strings hold exactly the same characters. compareTo reports which comes first, comparing character by character, as a number whose sign carries the answer. It's below 0 when the string it's called on comes first, 0 when they match, and above 0 when it comes later. For letters of the same case this is alphabetical order, and any capital letter sorts ahead of any small one.String other = "report_draft.pdf";
System.out.println(file.equals(other));
System.out.println(file.compareTo(other) > 0);
This prints
false and then true. The two strings agree through position 6. At position 7, file has f and other has d, and since f comes after d, file.compareTo(other) is positive. Nothing after the first difference matters.