/* 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(); //you could initialize a string like this: String myName = "Eliza"; System.out.println("Hi, my name is " + myName + ". What is your name?"); String first, last; System.out.print("First name: "); first = r.readString(); r.readLine(); System.out.print("Last name: "); last = r.readString(); r.readLine(); System.out.println("Nice to meet you, " + first + " " + last + "."); String x; x = "Computer Science"; System.out.println("Hope you enjoy your " + x +" class."); /* 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.equals(b)) System.out.println("The strings " + a + " and " + b + " are equal."); else System.out.println("The strings " + a +" and " + b + " are NOT equal."); if (a.equalsIgnoreCase(b)) System.out.println("The strings " + a + " and " + b + " are equal (if you ignore upper/lower case)."); else System.out.println("The strings " + a +" and " + b + " are NOT equal."); /* 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. Note that this method can be used to test whether a string is a substring of another one --- if this is not the case indexOf returns -1. */ int pos = first.indexOf("ny"); if (pos != -1) { System.out.print("ny" + " is a substring of " + first); System.out.println("It first occurs at position " + pos); } else System.out.println("ny" + " is NOT a substring of " + first); /* substring(int beginIndex) Returns a new string that is a substring of this string */ String s = first.substring(1, 4); System.out.println("The substring between positions 1 and 4 of " + myName + " is: " + s); } // end of main } // end of class