Java中字符串的使用方法
What are String Methods?
String in Java (Concatenation)
- Building longer strings from shorter strings
- String concatenation operator +
Scanner Methods
- next()
- nextLine()
String are chars sequences
String gretting = "Hello!";
0 | 1 | 2 | 3 | 4 | 5 |
---|---|---|---|---|---|
H | e | l | l | o | ! |
String Methods (CharAt)
Each char inside a String has an index number:
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---|---|---|---|---|---|---|---|---|---|
c | h | a | R | s | h | e | r | e |
- The first char is always at index zero(0)
- The charAt method returns a char at a given index inside a String
0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|
H | a | r | r | y |
public class greeting {
public static void main(String[] args) {
String greeting = "Harry";
char start = greeting.charAt(0);
// H
char last = greeting.charAt(4);
// y
}
}
String Methods(length)
- The length method returns the number of chars in the string
- Example
public class name {
public static void main(String[] args) {
String name = "Bob Smith";
System.out.print(name.length());
}
}
Output:
9
String Methods (substring)
The substring(a, b) methods returns a portion of the String.
- Staring at index a and ending before index b.
- Example
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
---|---|---|---|---|---|---|---|---|
B | o | b | S | m | i | t | h |
public class name {
public static void main(String[] args) {
String name = "Bob Smith";
System.out.print(name.substring(2, 6));
}
}
Output:
b Sm
String Methods(indexOf)
The indexOf(target) method returns start index of target in the String.
- return -1 if target not in the string.
- Example
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
---|---|---|---|---|---|---|---|---|
B | o | b | S | m | i | t | h |
public class name {
public static void main(String[] args) {
String name = "Bob Smith";
System.out.println(name.indexOf("b"));
System.out.println(name.indexOf("x"));
}
}
Output:
2
-1
String Methods(concat)
- The concat method returns a new string that appends s2 to s1.
- Example
public class name {
public static void main(String[] args) {
String s1 = "Hey";
String s2 = "!!!";
String output = s1.concat(s2);
System.out.println(output);
}
}
Output:
Hey!!!
评论已关闭