Chapter 5 Strings
Chapter 5 Strings
Unicode Format
- Java characters use Unicode, a 16-but encoding scheme to support interchange, processing, and
display of written text in world’s diverse languages.
- Unicode takes 2 bytes, preceded by \u, expressed in 4 hex-numbers from ‘\u0000’ to ‘\uFFFF’
- Unicode can represent 65535 + 1 characters.
- use nextLine() or next() method to read string and then invoke the charAt(0) method.
- For example:
Constructing a String:
- The method charAt(index) is used. The index is between 0 to the string length-1.
- For example, message.charAt (index)
Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message W e l c o m e t o J a v a
String Concatenation
- Use concat method:
String s3 = s1.concat(s2); //s1 and s2 into s3
String s3 = s1 + s1; // same effect
- Operator + can also concatenate a non-string with string ( at least one must be string)
- Can also use augmented += operator
- Example:
int i = 1;
int j = 2;
System.out.println(“i + j is” + i + j);
- Use next() method on a Scanner object. This method read a string that end with whitespace
character.
- For example:
- Use nextLine() method to read entire line of text. This method reads a string that ends with the
Enter key pressed. (line-based input)
- For example
Scanner input = new Scanner(System.in);
System.out.print(“Enter a message: “);
String msg = input.nextLine();
System.out.println(“The message entered is “ + msg);
- Caution (to avoid input error, don’t use line-based input after token-based input)
Comparing Strings
Obtaining Substrings
- You can obtain a substring from a string using the substring method in the String class.
Extracting Substrings
Finding a Character or a Substring in a String
“Welcome to Java”. indexOf(‘W’) returns 0
“Welcome to Java”. indexOf(‘x’) returns -1
- Return the index of the first character in the string that matches the specified character
- Frequently-Used Specifiers
Class methods:
Trigonometric Methods
Exponent Methods
Rounding Methods
Min, max, abs, random method