Java Strings
Slides provided by the University of Washington Computer Science & Engineering department.
Java Strings Slides provided by the University of Washington - - PowerPoint PPT Presentation
Java Strings Slides provided by the University of Washington Computer Science & Engineering department. Strings - string : an object storing a sequence of text characters. - Creating a string: String name = "text"; String name =
Slides provided by the University of Washington Computer Science & Engineering department.
String name = "text"; String name = expression;
String name = "Marty Stepp"; int x = 3; int y = 5; String point = "(" + x + ", " + y + ")";
String fruit = "Apple";
index
1 2 3 4
character
A p p l e
Method name Description int length() number of characters in this string String substring(int from, int to) returns the substring beginning at from and ending at to-1 String substring(int from) returns substring(from, length()) int indexOf(String str) returns the index of the first occurrence of str; returns -1 if not found int compareTo(String other) returns a value < 0 if this is less than other returns a value = 0 if this is equal to other returns a value > 0 if this is greater than other
String veggie = "carrot"; System.out.println(veggie.length()); // 6
// index 012345678901 String s1 = "Stuart Reges"; System.out.println(s1.length()); // 12 System.out.println(s1.indexOf("e")); // 8 System.out.println(s1.substring(7, 10)); // "Reg"
String message = "Hello, world!";
if (string1.equals(string2)) { System.out.println("The strings are equal!"); }
used in logical tests.
Write a static method numWords that takes a String as a parameter and that returns the number of words in the
more spaces.
numWords("how many?")
Returns 2
numWords(" how about a-b-c and !&%-$!*() ")
Returns 5 PROBLEM: EXAMPLES:
public static int numWords(String s) { int count = 0; boolean insideWord = false; for (int i = 0; i < s.length(); i++) { String current = s.substring(i, i + 1); if (current.equals(" ")) { insideWord = false; } else if (!insideWord) { count++; insideWord = true; } } return count; }
public static int numWords(String s) { int count = 0; String prev = " "; for (int i = 0; i < s.length(); i++) { String current = s.substring(i, i + 1); if (prev.equals(" ") && !current.equals(" ")) { count++; } prev = current; } return count; }