小树今天想跟大家分享一下Java中字符串String类常用方法示例,示例代码如下:
import java.util.*;
public class MultiArray {
public static void main(String[]args){
//Date date=new Date();
//System.out.println(date.toString());
testString();
}
public static void testString()
{
String s1=new String("welcome to Java!");
String s2="welcome to Jadvaaad!";
String s3=" ha ha ";
System.out.println(s1.equals(s2));
System.out.println(s2.compareTo(s2));
System.out.println(s1.compareTo(s3));//即从左到右第一个不同字符之间的距离
System.out.println(s1.length());
System.out.println(s1.charAt(3));//获得单个字符
System.out.println(s1.substring(3, 16));//从第4个到第16个组成的字符串
System.out.println(s1.substring(11));//第11个字符包括第11个组成的字符串
System.out.println(s1.concat(s3));//连接两个字符串
System.out.println(s1+s3);//连接两个字符串
System.out.println(s2.toLowerCase());
System.out.println(s2.toUpperCase());
System.out.println(s2);//s2字符串没有发生改变,除非给s2重新赋值
System.out.println(s3.trim());//去掉两端的空白字符
System.out.println(s3.replace(' ', 'i'));
System.out.println(s3.replaceFirst("ha", "hi"));
System.out.println(s3.replaceAll("ha", "hi"));
System.out.println(s3);
//System.out.println(s2.split("a",0));//这样写是错误的
String[]tokens=s2.split("a",0);//根据字符‘a’分割字符串(不要漏掉空字符串)
System.out.println("tokens里面字符串的个数:"+tokens.length);//特别注意aaa中间有两个空字符串
for(int i=0;i<tokens.length;i++)
{
System.out.print(tokens[i]);
}
System.out.println(s2.matches("welcome a.*"));//正则表达式 .*与0个或多个字符相匹配
String s4="a+b#c$db";
String s5=s4.replaceAll("[$+#]", "lhs");//使用正则表达式用字符串lhs替换原字符串中的¥、+、#,然后返回一个新字符串
System.out.println(s5);
String []t6="java,C?C#.,C++".split("[.,:?;]");//这里的正则表达式[.,:?;]指定的模式是指匹配。,:?; 将字符串按照标点符号分隔开
for(int i=0;i<t6.length;i++)
System.out.println(t6[i]);
System.out.println(s4.indexOf('b'));//返回字符串第一次出现字符'b'的下标
System.out.println(s4.indexOf('b',3));//返回下标3之后第一次出现字符'b'的下标
System.out.println(s4.lastIndexOf('b'));//返回字符串最后一次出现字符'b'的下标
System.out.println(s4.lastIndexOf('b',3));//返回下标3之前最后一次出现字符'b'的下标
char []chars=s4.toCharArray();//将字符串转换为字符数组
String h1="hahalklk";
h1.getChars(2, 5, chars, 2);//将字符串h1中下标从2到5-1=4的子串"ha"复制到字符数组chars中下标从2开始的位置
for(int i=0;i<chars.length;i++)
System.out.print(chars[i]);
System.out.println();
//将字符数组转换为字符串的两种方法
String Str1=String.valueOf(chars);
System.out.println(Str1);
String Str2=new String(new char[]{'a','b','c'});
System.out.println(Str2);
//格式化字符串
System.out.println(String.format("%.3f",45.556));//返回一个格式化字符串"45.456",必须有%,3表示小数点后保留三位
}
}
也可下载附件进行编译运行。