Java 字符串常用方法
判断类功能:
public class Main {
public static void main(String[] args) {
String s = "string123";
String s2 = "string321";
String s3 = "STring123";
String s4 = "string";
//判断字符串中的值是否相等
System.out.println(s.equals(s2));
//判断忽略大小写,判断字符串中的值是否相等
System.out.println(s.equalsIgnoreCase(s3));
//判断s4是否是s的子串(连续的)
System.out.println(s.contains(s4));
//判断s4是否是s的前缀
System.out.println(s.startsWith(s4));
//从下标为6初开始,判断"123"是否是前缀
System.out.println(s.startsWith("123", 6));
//判断s是否是以"123"为后缀
System.out.println(s.endsWith("123"));
}
}
获取类功能:
public class Main {
public static void main(String[] args) {
String s = "strging123";
//获取字符串长度
System.out.println(s.length());
//获取指定索引位置的字符
System.out.println(s.charAt(2));
//获取指定字符在此字符串中第一次出现的位置,如果不存在返回-1
//此处的字符也可以是整数,根据ASCII表
System.out.println(s.indexOf('g'));
//获取指定字符从指定位置(包括指定的位置)往后指定字符第一次出现的位置
System.out.println(s.indexOf('g', 4));
//过去指定字符串在此字符串中第一次出现的位置
System.out.println(s.indexOf("123"));
//获取指定字符串从指定位置(包括指定的位置)往后指定字符串第一次出现的位置
System.out.println(s.indexOf("123", 8));
//获取从指定位置开始截取的字符串
System.out.println(s.substring(2));
//获取从指定位置开始到指定位置结束的前一个位置的字符串
System.out.println(s.substring(1, 3));
}
}
转化类功能:
public class Main {
public static void main(String[] args) {
String s = "strING123";
//将字符串转化为字节数组
byte[] b = s.getBytes();
for(int i = 0; i < b.length; i++) {
System.out.print(b[i]+" ");
}
System.out.println();
//将字符串转化为字符数组
char[] a = s.toCharArray();
System.out.println(a);
a[1] = 'm';
System.out.println("改变后:");
for(int i = 0; i < a.length; i++) {
System.out.print(a[i]);
}
System.out.println();
//将字符数组转化为字符串
String s2 = String.valueOf(a);
System.out.println("转化为字符串:"+s2);
//将一个int类型的数据转化为字符串类型
//这个方法可以将任意类型的数据转化为字符串类型
System.out.println(String.valueOf(321));
//将字符串转化为小写
System.out.println(s.toLowerCase());
//将字符串转化为大写
System.out.println(s.toUpperCase());
//将字符串拼接到后边
System.out.println(s.concat("789"));
}
}
其他功能:
public class Main {
public static void main(String[] args) {
String s = "strING123";
String s2 = " jkll fff ";
//将字符串中指定字符改为另一个字符
System.out.println(s.replace('s', '6'));
//将字符串中指定子串改为另一个子串
System.out.println(s.replaceFirst("6tr", "str"));
//去除字符串,开头和结尾处的空格
System.out.println(s2.trim());
//区分大小写比较两个字符串,若相等返回0,s2比s大返回正数,否则返回负数
System.out.println(s2.compareTo(s));
//不区分大小写比较两个字符串,若相等返回0,s2比s大返回正数,否则返回负数
System.out.println(s2.compareToIgnoreCase(s));
}
}
还没有评论,来说两句吧...