(六)字符串
1.在这里需要指出的是它是一个对象,不是一个字符数组
2.他是不可变的,没有append()或reverse()
3.要用双引号,连接时用+
4.给出一些常用函数,相关的可查看API文档
toString();
int length() -- number of chars
char charAt(int index) -- char at given 0-based index
int indexOf(char c) -- first occurrence of char, or -1
int indexOf(String s)
boolean equals(Object) -- test if two strings have the same characters
boolean equalsIgnoreCase(Object) -- as above, but ignoring case
String toLowerCase() -- return a new String, lowercase
String substring(int begin, int end) -- return a new String made of the begin..end-1 substring from the original
5.初始化
s1 = new String(“This is some java String”);
s1 = new String(“This is some java String”);
6.例子
String a = "hello"; // allocate 2 String objects
String b = "there";
String c = a; // point to same String as a – fine
int len = a.length(); // 5
String d = a + " " + b; // "hello there"
int find = d.indexOf("there"); // find: 6
String sub = d.substring(6, 11); // extract: "there“
sub == b; // false (== compares pointers)
sub.equals(b); // true (a "deep" comparison)
String a = "hello"; // allocate 2 String objects
String b = "there";
String c = a; // point to same String as a – fine
int len = a.length(); // 5
String d = a + " " + b; // "hello there"
int find = d.indexOf("there"); // find: 6
String sub = d.substring(6, 11); // extract: "there“
sub == b; // false (== compares pointers)
Use the equals method;
s.equals(t) // returns true if the strings s and t are equal, false otherwise.
s and t can be string variables or string constants. "Hello".equals(command) // OK
To test if two strings are identical except for the upper/lowercase letter distinction
“Hello".equalsIgnoreCase("hello")
7.比较时一般不用==
String greeting = "Hello";
if (greeting == "Hello") . . . // probably true
if (greeting.substring(0, 4) == "Hell") . . . // probably false
8.StringBuffer
不同于String,
append() method- Lets you add characters to the end of a StringBuffer object
insert() method- Lets you add characters at a specified location within a StringBuffer object
setCharAt() method- Use to alter just one character in a StringBuffer
例子:
StringBuffer buff = new StringBuffer();
for (int i=0; i<100; i++) {
buff.append(<some thing>);
// efficient append
}
String result = buff.toString();
// make a String once done with appending
9.StringTokenizer
可以根据某些标记(token),来分割String
例子:
String testString = “one-two-three”;
StringTokenizer st = new StringTokenizer(testString,”-");
while (st.hasMoreTokens()) {
String nextName = st.nextToken();
System.out.println(nextName);
}
Result:
one
two
three
评论
推荐阅读
留下你的脚步