/* This is a program that demonstrates strings and methods you can use on strings. Laura Toma csci107 */ public class StringStarter { public static void main (String args[]) { //setting up the variable that reads from user ReadStream r = new ReadStream(); String first, last, myName; System.out.print("First name: "); first = r.readString(); r.readLine(); System.out.print("Last name: "); last = r.readString(); r.readLine(); //or, you could initialize a string like this: myName = "Johny"; System.out.println("Nice to meet you, " + first + " " + last + "."); System.out.println("My name is " + myName + "."); /* Below are some methods that you can use on strings. All these methods can be used on any variable of type String, by using the variable name (identifier), followed by a dot, followed by the method name (and the required arguments, if any). String s; //read s from user with r.readString(), or assign s = "abc" then you can use s.substring(,), s.equals() s.indexAt() */ /* boolean equals(String anotherString) Compares this string to the specified anotherString. The result is true if and only if the argument represents the same sequence of characters as this string. Case matters. */ if (first.equals(myName)) System.out.println("We have the same name!!"); else System.out.println("We do not have the same name."); /* boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations. */ String a = "Mac", b = "mac"; if (a.equalsIgnoreCase(b)) System.out.println("The strings " + a + " and " + b + " are equal."); else System.out.println("The strings " + a +" and " + b + " are NOT equal."); /* substring(int beginIndex) Returns a new string that is a substring of this string */ String s = myName.substring(1, 3); System.out.println("The substring between positions 1 and 3 of " + myName + " is: " + s); /* int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. That is, if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned. */ int pos = myName.indexOf("ny"); if (pos != -1) { System.out.print("ny" + " is a substring of " + myName); System.out.println("It first occurs at position " + pos); } else System.out.println("ny" + " is NOT a substring of " + myName); } // end of main } // end of class