Beruflich Dokumente
Kultur Dokumente
• The String class has 13 constructors and more than 40 methods for manipulating
strings.
Indexes
• Characters of a string are numbered with 0-based
indexes: index 0 1 2 3 4 5 6 7
char M r J a m e s
indexOf(str) index where the start of the given string appears in this string (-1 if it
is not there)
// “MR JAMES"
Modifying strings
• Methods like toLowerCase, toUpperCase, etc. create/return
a new string, rather than modifying the current string.
String name = “Mr James";
System.out.println(name.toUpperCase()); // MR JAMES
System.out.println(name); // Mr James
System.out.println(name.substring(0)); // Mr James
System.out.println(name.substring(0,2)); // Mr
System.out.println(name.substring(3));// James
System.out.println(name.substring(3, 6)); // Jam
String methods – substring(start, end-1)
String word = "development";
// 0 1 2 3 4 5 6 7 8 9 10
// d e v e l o p m e n t
System.out.println(word.substring(0,7));
System.out.println(word.substring(8,10) + word.substring(2,7));
System.out.println(word.substring(1, 4) + word.substring(9));
System.out.println(word.substring(7) + word.substring(5, 6) + word.substring(4, 5));
Strings as parameters
public class StringParameters {
public static void main(String[] args) {
sayHello("Marty");
Output:
Welcome, Marty
Welcome, Helen
Strings as user input
• Scanner's next method reads a word of input as a String.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
name = name.toUpperCase();
System.out.println(name + " has " + name.length() +
Output:
What is your name? Madonna
MADONNA has 7 letters and starts with M
– This code will compile, but it will not print the song.
if(name.startsWith("Ms."))
System.out.println("Single");
else if (name.equalsIgnoreCase("Mrs."))
System.out.println("Married");
String test methods
Method Description
compareTo(s1: String) Returns an integer greater than 0, equal to 0, or less than
0 to indicate whether this string is greater than, equal to,
or less than s1
System.out.println(s1.compareTo(s2)); // 0
System.out.println(s1.compareToIgnoreCase(s3)); // 0
Strings question
• Write a program that reads a person's name and converts it into a "gangsta
name."
– Examples:
'A' is 65, 'B' is 66, ' ' is 32
'a' is 97, 'b' is 98, '*' is 42
• What is s + 1 ? What is c + 1 ?
• What is s + s ? What is c + c ?
Comparing char values
• You can compare char values with relational operators:
'a' < 'b' and 'X' == 'X' and 'Q' != 'q'