Java 基础之String类

1.String类初始化方法;

public class Main {

    public static void main(String[] args) {
         String str1=new String("hello");

         String str2="hello";

         char[] chars=new char[]{'h','e','l','l','o'};
         String str3=new String(chars);

         String str4=new String(chars,1,4);
         
         System.out.println("Str1: "+str1);
         System.out.println("Str2: "+str2);
         System.out.println("Str3: "+str3);
         System.out.println("Str4: "+str4);

    }
}

运行结果:

2.String类 常用方法

str1.concat(String str2). //连接字符串,返回新字符串

str1.charAt(index i) //按下标查找字符

str1.length() //得到字符串长度

str1.indexOf(String s)//字符串查找,返回子串s的起始地址

str1.lastIndexOf(String s)//查找字符串s 最后一次出现的位置

str1.substring(int beginIndex). //从beginIndex 开始截取字符串 ,返回新字符串

str1.substring(int beginIndex,int endIndex) //从beginIndex开始到endIndex结束,截取字符串,返回新字符串

str1.trim() //去除空格,返回新字符串

str1.replace(原字符或字符串,新字符或字符串) //字符串替换,返回新字符串

str1.startWith(String s) //判断字符串是不是以s开头

str1.endWith(String s)//判断字符串是不是以s结尾

str1.equals(Sting s)//比较字符串内容

str1.equalsIgnoreCase(String s)//忽略大小写比较字符串内容是否相等

str1.compareTo(String s)//按字典序比较,返回值-1,0,1分别表示比较s的时候在s之前、相等,之后的情况

str1.toLowerCase()//将字符串都变成小写

str1.toUpperCase()//将字符串都编程大写

str1.split(string s)//根据字符串s对str1进行分割,返回字符串数组

str1.split(string s,int limit)////根据字符串s对str1进行分割且限定分割片段数,返回字符串数组

3.字符串格式化

str1.format(String fomate,Object... args)

如:

String str7=String.format("Hi,%s", "你好");
System.out.printf("hello %s","world");

猜你喜欢

转载自blog.csdn.net/qq_35464253/article/details/81139605