字符串比较
通过字符串函数 compareTo (string) ,compareToIgnoreCase(String) 及 compareTo(object string) 来比较两个字符串,并返回字符串中第一个字母ASCII的差值。
package com.csu.test;
public class Test {
public static void main(String args[]) {
String str = "Hello World";
String anotherString = "hello world";
Object objStr = str;
System.out.println(str.compareTo(anotherString));
System.out.println(str.compareToIgnoreCase(anotherString)); // 忽略大小写
System.out.println(str.compareTo(objStr.toString()));
}
}
输出结果:
-32 0 0
查找字符串最后一次出现的位置
通过字符串函数 strOrig.lastIndexOf(Stringname) 来查找子字符串 Stringname 在 strOrig 出现的位置:
package com.csu.test;
public class Test {
public static void main(String[] args) {
String strOrig = "Hello world ,Hello Runoob";
int lastIndex = strOrig.lastIndexOf("Runoob");
if (lastIndex == -1) {
System.out.println("没有找到字符串 Runoob");
} else {
System.out.println("Runoob 字符串最后出现的位置: " + lastIndex);
}
}
}
以上代码实例输出结果为:
Runoob 字符串最后出现的位置: 19
删除字符串的一个字符
通过字符串函数 substring() 函数来删除字符串中的一个字符,我们将功能封装在 removeCharAt 函数中。
package com.csu.test;
public class Test {
public static void main(String args[]) {
String str = "this is Java";
System.out.println(removeCharAt(str, 3));
}
public static String removeCharAt(String s, int pos) {
return s.substring(0, pos) + s.substring(pos + 1);
}
}
运行结果:
thi is Java
字符串反转
使用 Java 的反转函数 reverse() 将字符串反转:
package com.csu.test;
public class Test {
public static void main(String[] args) {
String string = "runoob";
//通过StringBuffer来实现字符串反转
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("字符串反转前:" + string);
System.out.println("字符串反转后:" + reverse);
}
}
以上代码实例输出结果为:
字符串反转前:runoob 字符串反转后:boonur
字符串搜索
使用了 String 类的 indexOf() 方法在字符串中查找子字符串出现的位置,如果存在返回字符串出现的位置(第一位为0),如果不存在返回 -1:
package com.csu.test;
public class Test {
public static void main(String[] args) {
String strOrig = "Google Runoob Taobao";
int intIndex = strOrig.indexOf("Runoob");
if(intIndex == - 1){
System.out.println("没有找到字符串 Runoob");
}else{
System.out.println("Runoob 字符串位置 " + intIndex);
}
}
}
以上代码实例输出结果为:
Runoob 字符串位置 7
字符串分割
使用了 split(string) 方法,通过指定分隔符,将字符串分割为数组:
package com.csu.test;
public class Test {
public static void main(String args[]) {
String str = "www-runoob-com";
String[] temp;
String delimeter = "-"; // 指定分割字符
temp = str.split(delimeter); // 分割字符串
// 普通 for 循环
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
System.out.println("");
}
System.out.println("------java for each循环输出的方法-----");
String str1 = "www.runoob.com";
String[] temp1;
String delimeter1 = "\\."; // 指定分割字符, . 号需要转义
temp1 = str1.split(delimeter1); // 分割字符串
for (String x : temp1) {
System.out.println(x);
System.out.println("");
}
}
}
以上代码实例输出结果为:
www runoob com ------java for each循环输出的方法----- www runoob com
字符串分隔(StringTokenizer)
可以使用 StringTokennizer 设置不同分隔符来分隔字符串。默认的分隔符是:空格、制表符(\t)、换行符(\n)、回车符(\r)。
以下实例演示了 StringTokennizer 使用空格和逗号来分隔字符串:
package com.csu.test;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
String str = "This is String , split by StringTokenizer, created by runoob";
//1.默认空格分隔
StringTokenizer st = new StringTokenizer(str);
System.out.println("----- 通过空格分隔 ------");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
//2.指定用逗号分隔
System.out.println("----- 通过逗号分隔 ------");
StringTokenizer st2 = new StringTokenizer(str, ",");
while (st2.hasMoreElements()) {
System.out.println(st2.nextElement());
}
}
}
输出结果:
----- 通过空格分隔 ------ This is String , split by StringTokenizer, created by runoob ----- 通过逗号分隔 ------ This is String split by StringTokenizer created by runoob
字符串小写转大写
使用了 String toUpperCase() 方法将字符串从小写转为大写:
public class StringToUpperCaseEmp {
public static void main(String[] args) {
String str = "string runoob";
String strUpper = str.toUpperCase();
System.out.println("原始字符串: " + str);
System.out.println("转换为大写: " + strUpper);
}
}
以上代码实例输出结果为:
原始字符串: string runoob 转换为大写: STRING RUNOOB
测试两个字符串区域是否相等
使用了 regionMatches() 方法测试两个字符串区域是否相等:
package com.csu.test;
public class Test {
public static void main(String[] args) {
String first_str = "Welcome to Microsoft";
String second_str = "I work with microsoft";
boolean match1 = first_str.regionMatches(11, second_str, 12, 9);
// 第一个参数 true 表示忽略大小写区别
boolean match2 = first_str.regionMatches(true, 11, second_str, 12, 9);
System.out.println("区分大小写返回值:" + match1);
System.out.println("不区分大小写返回值:" + match2);
}
}
first_str.regionMatches(11, second_str, 12, 9) 表示将 first_str 字符串从第11个字符"M"开始和 second_str 字符串的第12个字符"M"开始逐个比较,共比较 9 对字符,由于字符串区分大小写,所以结果为false。
如果设置第一个参数为 true ,则表示忽略大小写区别,所以返回 true。
以上代码实例输出结果为:
区分大小写返回值:false 不区分大小写返回值:true
创建字符串 性能比较测试
通过两种方式创建字符串,并测试其性能:
package com.csu.test;
public class Test {
public static void main(String[] args) {
// 1
long startTime = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
String s1 = "hello";
String s2 = "hello";
}
long endTime = System.currentTimeMillis();
System.out.println("通过 String 关键词创建字符串" + " : " + (endTime - startTime) + " 毫秒");
// 2
long startTime1 = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
String s3 = new String("hello");
String s4 = new String("hello");
}
long endTime1 = System.currentTimeMillis();
System.out.println("通过 String 对象创建字符串" + " : " + (endTime1 - startTime1) + " 毫秒");
}
}
以上代码实例输出结果为:
通过 String 关键词创建字符串 : 1 毫秒 通过 String 对象创建字符串 : 4 毫秒
字符串优化
通过 String.intern() 方法来优化字符串:
package com.csu.test;
public class Test {
public static void main(String[] args) {
String variables[] = new String[50000];
for (int i = 0; i < 50000; i++) {
variables[i] = "s" + i;
}
//1
long startTime0 = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
variables[i] = "hello";
}
long endTime0 = System.currentTimeMillis();
System.out.println("直接使用字符串: " + (endTime0 - startTime0) + " ms");
//2
long startTime1 = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
variables[i] = new String("hello");
}
long endTime1 = System.currentTimeMillis();
System.out.println("使用 new 关键字:" + (endTime1 - startTime1) + " ms");
//3
long startTime2 = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
variables[i] = new String("hello");
variables[i] = variables[i].intern();//把字符串对象加入常量池中,因为从常量池取数据比从堆里面去数据要快一些
}
long endTime2 = System.currentTimeMillis();
System.out.println("使用字符串对象的 intern() 方法: " + (endTime2 - startTime2) + " ms");
}
}
直接使用字符串: 3 ms 使用 new 关键字:5 ms 使用字符串对象的 intern() 方法: 10 ms
字符串格式化
通过 format() 方法来格式化字符串,还可以指定地区来格式化:
package com.csu.test;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
double e = Math.E;
System.out.format("%f%n%n", e);
System.out.format(Locale.CHINA, "%-10.4f%n", e); // 指定本地为中国(CHINA)
}
}
以上代码实例输出结果为:
2.718282 2.7183
连接字符串
通过 "+" 操作符和StringBuffer.append() 方法来连接字符串,并比较其性能:
package com.csu.test;
public class Test {
public static void main(String[] args) {
// 1
long startTime = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
String result = "This is" + "testing the" + "difference" + "between" + "String" + "and" + "StringBuffer";
}
long endTime = System.currentTimeMillis();
System.out.println("字符串连接" + " - 使用 + 操作符 : " + (endTime - startTime) + " ms");
// 2
long startTime1 = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
StringBuffer result = new StringBuffer();
result.append("This is");
result.append("testing the");
result.append("difference");
result.append("between");
result.append("String");
result.append("and");
result.append("StringBuffer");
}
long endTime1 = System.currentTimeMillis();
System.out.println("字符串连接" + " - 使用 StringBuffer : " + (endTime1 - startTime1) + " ms");
}
}
以上代码实例输出结果为:
字符串连接 - 使用 + 操作符 : 0 ms 字符串连接 - 使用 StringBuffer : 6 ms