文字字串是一个相当基本且经常被使用到的资料型态,然而在 Java 中字串不象 char、int 与 float
一样是个基本资料型态,而是使用 java.lang.String 类别来加以表示,该类别定义了许多有用的方法来操作字串。String
物件是固定不变的(immutable):一旦一个 String
物件被建立了,则没有任何方法可以改变它所代表的文字,因此,每个运作字串的方法会传回一个新的 String
物件,而所修正过后的字串便是储存在此新物件里。
以下的程式码展示了你可以对字串所执行的运作:
// 建立字串
String s = "Now"; // String 物件有个特殊的写法
String t = s + " is the time."; // 使用 + 运算子来串连字串
String t1 = s + " " + 23.4; // + 将其它值转换为字串
t1 = String.valueOf('c'); // 从字元值获得对应的字串
t1 = String.valueOf(42); // 获得整数或其他任何数值的字串版本
t1 = Object.toString(); // 使用 toString() 将物件转换为字串
// 字串长度
int len = t.length(); // 字串中的字元数:16
// 字串中的子字串
String sub = t.substring(4); // 传回从 char 4 到最后的子字串:"is the time."
sub = t.substring(4, 6); // 传回 chars 4 与 5:"is"
sub = t.substring(0, 3); // 传回 chars 0 到 2:"Now"
sub = t.substring(x, y); // 传回从位置 x 到 y-1 间的子字串
int numchars = sub.length(); // 子字串的长度永远是 (y-x)
// 从一个字串中撷取(extract)出字元
char c = t.charAt(2); // 取得 t 的第三个字元:w
char[] ca = t.toCharArray(); // 将字串转换为一个字元阵列
t.getChars(0, 3, ca, 1); // 将 t 中的前三个字元放到 ca[1] 到 ca[3] 中
// 大小写转换
String caps = t.toUpperCase(); // 转换为大写
String lower = t.toLowerCase(); // 转换为小写
// 字串比较
boolean b1 = t.equals("hello"); // 传回 flase:两字串并不相等
boolean b2 = t.equalsIgnoreCase(caps); // 忽略大小写的字串比较:true
boolean b3 = t.startsWith("Now"); // 传回 true
boolean b4 = t.endsWith("time."); // 传回 true
int r1 = s.compareTo("Pow"); // 传回值 <0:s 在"Pow"之前
int r2 = s.compareTo("Now"); // 传回值 0:两字串相等
int r3 = s.compareTo("Mow"); // 传回值 >0:s 在"Mow"之后
r1 = s.compareToIgnoreCase("pow"); // 传回值 <0(Java 1.2 之后才支援)
// 搜寻字元与子字串
int pos = t.indexOf('i'); // 'i' 的位置:4
pos = t.indexOf('i', pos + 1); // 下一个 'i' 的位置:12
pos = t.indexOf('i', pos + 1); // 字串中已经没有 'i' 了,传回 -1
pos = t.lastIndexOf('i'); // 字串中最后一个 'i' 的位置:12
pos = t.lastIndexOf('i', pos - 1); // 从 char 11 开始往前搜寻 'i'
pos = t.indexOf("is"); // 搜寻子字串:传回 4
pos = t.indexOf("is", pos + 1); // 只出现一次:传回 -1
pos = t.lastIndexOf("the"); // 由后往前搜寻字串
String noun = t.substring(pos + 4); // 撷取出 "the" 之后的字串
// 将某个字元实体转换为另一个字元
String exclaim = t.replace('.', '!'); // 只能与字元一起使用,不能与子字串一起使用
// 将字串最前面的与最后面的空白删除
String noextraspaces = t.trim();
// 使用 intern() 获得独有的字串实体
String s1 = s.intern(); // 传回 s1,相等于 s
String s2 = "Now".intern(); // 传回 s2,相等于 "Now"
boolean equals = (s1 == s2); // 以 == 测试 s1、s2 是否相等
String temp = " woaizhonghua " ;
String temp1 = temp.replaceAll( " (wo|ai|zhong|hua) " , " $1, " );
System.out.println(temp1.substring( 0 ,temp1.length() - 1 ));