// Strings are one of the most common data types in Java
// A String contains a sequence of characters (its data), along
// with methods (operations) that can apply to that data import java.util.*; public class StringExamples { public static void main (String [ ] args) { Scanner input = new Scanner(System.in); // A string consists of a quoted series of characters // A String is a reference type -- it has data and code, and is stored // in a two-part structure (primitive types like int and float h ave // a one-part structure). The variable name stores the memory ad dress // where the actual data is stored in memory String s = // Step 1: // Step 2: // Step 3: // Step 4:
new String("abcdef"); Create a reference variable s that points to a String Create a new String-sized object in memory Initialize the new String with the date "abcdef" Assign the memory location of our new String to s
// Thanks to Java's "syntactic sugar", we have a simpler way
// to create a String variable (this notation ONLY works for // Strings, not for other types of objects): String a = "foobar123"; // String operations include the following: // length() -- # of characters in the string int len = a.length(); System.out.println(a + " has " + len + " characters"); // Use + to concatenate two or more Strings a = a + s; System.out.println(a); // toUpperCase() and toLowerCase() do what you would expect; NOT E that // they DO NOT change the original String System.out.println(s.toUpperCase()); System.out.println(s); // Use charAt() and indexOf() to query a String for information // charAt() returns the character at a specific position. Charac ter positions // are numbered starting with 0 and running up to (length-1). // indexOf() returns the position of a specific substring, or -1 if not found System.out.print("Enter some text: "); String text = input.nextLine(); System.out.println("The 3rd character is " + text.charAt(2));
System.out.print("Enter text to find: ");
String toFind = input.nextLine(); int pos = text.indexOf(toFind); System.out.println("Found at position " + pos); // substring() allows us to extract part of a String // Form 1: substring(a, b) gives all characters from a up to but not including b // Form 2: substring(a) gives all characters from a through end // example: Given a sequence "AAA BBB CCC" where we know that BB B is always 3 // characters long, but AAA and CCC can be any length, how do we extract just // BBB from the input System.out.print("Enter line of data: "); String data = input.nextLine(); int space = data.indexOf(" "); if (space == -1) // not found { System.out.println("ERROR in input format!"); } else { // Check to see if the String contains a second space (m eaning // there are at least three "words") if (data.indexOf(" ", space+1) != -1) { // Extract three characters from the second/midd le "word" String extracted = data.substring(space+1, space +4); System.out.println("Extracted field is " + extra cted); } else { System.out.println("Malformed input"); } } // Use the replace() method to change all occurrences of a // specific substring // // Usage: source-string.replace(text_to_search_for, replacement_ text) System.out.print("Enter some more text: "); String textBlock = input.nextLine(); System.out.print("Enter text to replace: "); String source = input.nextLine(); System.out.print("Enter text to replace it with: "); String newText = input.nextLine(); String replaced = textBlock.replace(source, newText); System.out.println(replaced);
// Use the trim() command to remove any leading or trailing
// whitespace (but not whitespace between words) String fullOfWhitespace = " adghsuoag dsgafo dsahlj "; System.out.println("[" + fullOfWhitespace + "]"); // Apply trim(): fullOfWhitespace = fullOfWhitespace.trim(); System.out.println("[" + fullOfWhitespace + "]"); // String comparisons String first = "abcdef"; String second = "abc"; second = second + "def"; System.out.println("Comparing " + first + " to " + second); if (first == second) { System.out.println("They are the same"); } else { System.out.println("They are different"); } // == performs a SHALLOW comparison -- it only checks the value // immediately associated with a variable. In the case of a Stri ng, // this means that it looks at the memory address where the data // is stored, rather than the actual data // The String method equals() performs a DEEP comparison, where it // looks at the actual end data for its comparison if (first.equals(second) == true) { System.out.println("They are the same"); } else { System.out.println("They are different"); } // equals() has a case-insensitive option named: equalsIgnoreCas e() // The same thing happens for comparisons between Strings. Use t he // compareTo() operation to figure out greater than/less than re lations // // // // //
a.compareTo(b) is negative is a < b
a.compareTo(b) is 0 if a and b are equal a.compareTo(b) is positive is a > b (greater than = comes later in the alphabet)
System.out.print("Enter first string to compare: ");
String comp1 = input.nextLine(); System.out.print("Enter second string to compare: ");
String comp2 = input.nextLine();
System.out.println("CompareTo() result: " + comp1.compareTo(comp 2)); // We can use compareToIgnoreCase() to perform a case-insensitiv e comparison System.out.println("CompareToIgnoreCase(): " + comp1.compareToIg noreCase(comp2)); } }