String的常用操作
字节数组--->字符串
> public class Test {
> public static void main(String[] args) {
> String str ="adcde";
> byte[] bs = str.getBytes();//将字符串变成byte类型数组
> String str1 = new String(bs,0,5);//将0~5的字符数组重新变为String
> String str2 = new String(bs);//将全部的字符数组重新变为String
> System.out.println(str1);
> System.out.println(str2);
> }
> }
判断是否以指定的字符串开头或结尾:
•判断是否以指定的字符串开头:public boolean startsWith(String prefix)
•判断是否以指定的字符串结尾:public boolean endsWith(String suffix)
•范例:
public class Test {
public static void main(String[] args) {
String str ="**adcde##";
System.out.println(str.startsWith("**"));
System.out.println(str.endsWith("##"));
}
}
替换操作:
使用以下方法能完成替换操作:
public String replaceAll(String regex, String replacement)
•范例:
public static void main(String[] args) {
String str ="hello world";
String str1 = str.replaceAll("l", "x");
System.out.println(str1);
}
输出结果为:hexxo worxd
字符串截取:
使用以下方法完成字符串截取操作:
•全部截取:
public String substring(int beginIndex)
•部分截取:
public String substring(int beginIndex,int endIndex)
•范例
public static void main(String[] args) {
String str ="hello world";
String str1 = str.substring(6);
String str2 = str.substring(0, 5);
System.out.println(str1);
System.out.println(str2);
}
输出结果为 :
str1=world;
str2=hello;
字符串拆分:
可以将字符串按照指定的内容进行拆分:
public String[] split(String regex)
•范例:按照空格进行拆分
public static void main(String[] args) {
String str ="hello wlord";
String[] split = str.split(" ");
for (String string : split) {
System.out.println(string);
}
}
字符串查找:
在字符串中查找指定的内容是否存在用以下方法:
1:取得指定字符串的位置
public int indexOf(int ch)
此方法返回值为int类型,如果找到则返回位置,如果找不到则返回-1
•范例:
public static void main(String[] args) {
String str ="hello wlord";
System.out.println(str.indexOf("hello"));
System.out.println(str.indexOf("csdn"));
}
2:直接查找
public boolean contains(String s)
•范例:
public static void main(String[] args) {
String str ="hello wlord";
System.out.println(str.contains("hello"));
System.out.println(str.contains("csdn"));
}
-
字符串的其他操作
取得字符串的长度: public int length() 去掉左右两边空格: public String trim() 转大写 public String toUpperCase() 转小写 public String toLowerCase()