String 1 Notes
String 1 Notes
Lecture 5
CGS 3416 Spring 2020
Don’t try to compare strings by using ==, <, >, etc. These would
only compare the String reference variables, not the String objects
themselves.
The equals() method
if (str1.equals(str2))
System.out.print("The strings are the same");
if (str1.compareTo(str2) <0)
System.out.print("str1 comes before str2 in
lexicographic ordering");
else if (str1.compareTo(str2) == 0)
System.out.print("str1 is the same as str2");
else if (str1.compareTo(str2) >0)
System.out.print("str2 comes before str1 in
lexicographic ordering");
Empty Strings
Note that if you only declare a String variable, but you do not
assign it to anything, it is not yet attached to any string:
String s1 = "Dog";
String s2 = "food";
String s3 = s1.concat(s2);
//s3 now stores "Dogfood"
//note: s1 and s2 are NOT changed
I The + symbol also performs String concatenation (as we’ve
already used in print statements).
String s1 = "Cat";
String s2 = "nap";
String s3 = s1 + s2;
//s3 now stores "Catnap" (s1, s2 unchanged)
Substrings
System.out.print(s1.length()); // output: 5
System.out.print(s2.length()); // output: 13
charAt() method
System.out.print(s1.charAt(0)); // output: R
System.out.print(s1.charAt(5)); // output: e
System.out.print(s1.charAt(12)); // output: k
Some Conversion methods
String s1 = "Zebra
String x = "1";
String y = "2";
System.out.println(x+y);
int i = Integer.parseInt(x);
int j = Integer.parseInt(y);
System.out.println(i+j);
System.out.println(gpa2 - 1.0);
The StringBuilder Class
buf1.append("Hello");
buf1.append(‘,’);
buf1.append(" world!");
// buf1 is now "Hello, world!"
buf1.append(‘ ’);
buf1.append(123.45);
// buf1 is now "Hello, world! 123.45"
The insert() method
buf2.append("Welcome home");
// buf2 now "Welcome home"
buf3.delete(4,9);
// deletes indices 4-8. buf3 is now "abcdjklm"