package com.company;
import java.util.*;
/*
常用的一些方法操作
字符串比较
查找字符串最后一次出现的位置
删除字符串中的一个字符
字符串替换
字符串反转
字符串查找:String 类的 indexOf() 方法在字符串中查找子字符串出现的位置,如果存在返回字符串出现的位置(第一位为0),如果不存在返回 -1:
字符串分割
字符串分割(StringTokenizer)
字符串小写转大写
测试两个字符串区域是否相等
字符串性能比较测试
*/
public class StringTest {
public static void main(String[] args) {
String str = "hello world,i am boss,QQQQQ,ee eee";
String str2 = "world hello";
Object obStr = str;
//比较字符串
System.out.println(str.compareTo(str2));
System.out.println(str.compareToIgnoreCase(str2));
System.out.println(str.compareTo(obStr.toString()));
//查看字符串出现的位置
int firstIndex = str.indexOf("l");
int lastIndex = str.lastIndexOf("am");
System.out.println("首次出现的位置:" + firstIndex + " 最后一次出现的位置" + lastIndex);
//删除字符串中的一个字符
String newStr = str.substring(0, 3) + str.substring(4);
System.out.println(newStr);
//字符串替换
String newStr1 = str.replace("h", "G");
String newStr2 = str.replaceFirst("am", "an");
String newStr3 = str.replaceAll("l", "q");
System.out.println("newStr1:" + newStr1);
System.out.println("newStr2:" + newStr2);
System.out.println("newStr3:" + newStr3);
//字符串反转
String string = "runoob";
String reverse = new StringBuilder(string).reverse().toString();
System.out.println("字符串反转前:" + string);
System.out.println("字符串反转后:" + reverse);
//字符串分割
String str3 = "www.baidu.com";
String[] temp1;
String delimeter = "\\."; // 指定分割字符
temp1 = str3.split(delimeter);
System.out.println(Arrays.toString(temp1));
for (String x : temp1) {
System.out.println(x);
}
//字符串分隔(StringTokenizer)
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreElements()) {
System.out.println("StringTokenizer1:" + st.nextElement());
}
StringTokenizer st2 = new StringTokenizer(str, ",");
while (st2.hasMoreElements()) {
System.out.println("StringTokenizer2:" + st2.nextElement());
}
//符串小写转大写
String str6 = "AAA bbbb CCCC";
//小写转大写
String newStr6 = str6.toUpperCase();
//大写转小写
String newstr62 = str6.toLowerCase();
System.out.println("newStr6:" + newStr6);
//测试两个字符串区域是否相等
String first_str = "Welcome to Microsoft";
String second_str = "I work with microsoft";
boolean match1 = first_str.regionMatches(11, second_str, 12, 9);
//不区分大小写
boolean match2 = first_str.regionMatches(true, 11, second_str, 12, 9);
System.out.println("match1:" + match1 + " match2:" + match2);
//字符串性能比较测试
long startTime1 = System.currentTimeMillis();
for (int i = 0; i < 500000; i++) {
String strStr1 = "hello";
String strStr2 = "world";
}
long endTime1 = System.currentTimeMillis();
System.out.println("通过 String 关键词创建字符串 :" + (endTime1 - startTime1) + " 毫秒");
long startTime2 = System.currentTimeMillis();
for (int i = 0; i < 500000; i++) {
String strStr3 = new String("hello");
String strStr4 = new String("world");
}
long endTime2 = System.currentTimeMillis();
System.out.println("通过 String 对象创建字符串 :" + (endTime2 - startTime2) + " 毫秒");
}
}
网友评论