public static void main(String[] args) {
/**
* 空格 = 1 个字符
*/
String value = "this is test value";
/**
* 判断字符串是否是空
*/
boolean isNull = value.isEmpty();
System.out.println(isNull);// false
/**
* equals 比较是否相等
*/
boolean isEqual = value.equals("other string");
System.out.println(isEqual);// false
/**
* 116 是 t 的字符吗
* indexOf(数字)
* 通过字符码查询字符串内是否有这个值
* 如果有 就返回第一次出现的位置
* indexOf 如果没找到都是返回 -1
*/
int index = value.indexOf(116);
System.out.println(index);// 0
/**
* 查询字符串内是否包含某字符串
* 返回值 第一次出现的位置
*/
int ind = value.indexOf("s");
System.out.println(ind);// 3
/**
* 从第 n 个字符往后查询 字符串 第一次出现的位置
*/
int idx = value.indexOf("s",8);
System.out.println(idx);// 10
/**
* 查询字符串最后出现的索引位置
*/
int lastIdx = value.lastIndexOf("s");
System.out.println(lastIdx);// 10
/**
* 判断字符串是否已 某字符串 开头
*/
boolean startW = value.startsWith("this");
System.out.println(startW);// true
/**
* 从第 n 个字符开始计算 是否已 某字符串 开头
*/
boolean startWith = value.startsWith("is",5);
System.out.println(startWith);// true
/**
* 判断字符串是否已 某字符串 结尾
*/
boolean endWith = value.endsWith("value");
System.out.println(endWith);// true
/**
* 按空格拆分字符串
* 当然你也可以自己选择按什么拆分
*/
String[] strings = value.split(" ");
for (String str : strings) {
System.out.print(str + "-");//this-is-test-value-
}
/**
* 这个没有多大意义
* 只是换行输出而已
*/
System.out.println();
/**
* 按空格拆分
* 在第 n 次出现空格的地方停止拆分
*/
String[] strArr = value.split(" ",2);
for (String s : strArr) {
System.out.printf(s +"--");//this--is test value--
}
System.out.println();
/**
* 第一个参数 是要被替换的值
* 第二个参数 是替换后的得到的值
*/
String newValue = value.replace("is","12");
System.out.println(newValue);//th12 12 test value
/**
* 只替换第一个次出现的值
* 第一个参数可以写正则表达式
*/
String firstR = value.replaceFirst("i","1");
System.out.println(firstR);// th1s is test value
/**
* 第一个参数可以写正则表达式
* 也可以和 replace 方法一样使用
* \\s 在正则内 == 空白字符
*/
String allR = value.replaceAll("\\s","--");
System.out.println(allR);// this--is--test--value
/**
* 查询索引位置对应位置的字符
*/
char charAt = value.charAt(2);
System.out.println(charAt);// i
/**
* 查询对应索引位置字符的字符码
*/
int code = value.codePointAt(2);
System.out.println(code);// 105
/**
* 字符串拼接
* 性能高于 + 拼接
* 如果是频繁拼接推荐使用 concat
*/
String concatV = value.concat(" then i add new value");
System.out.println(concatV);// this is test value then i add new value
}
java String常用方法及说明
最新推荐文章于 2024-08-18 23:25:39 发布