String类,StringBuffer类以及区别

目录

一,String类

二. String常用的方法

(1)获取字符串长度以及访问字符串中的字符

(2)字符串的转换操作

(3)字符串的替换和去空格操作

(4)字符串判断

(5)字符串的截取和分割操作

三.StringBuffer类

四.StringBuilder类、StringBuffer类和String类区别


String,StringBuilder区别

一,String类

初始化:

1.String 变量名=字符串;


String str1=null;//将字符串str1设为空
String str2="";//设为空
String str3="asd";
String len="asdf".length();//字符串包含字符的个数

2.String 变量名=new String(字符串);


String类的常见构造方法
方法声明功能描述
String()创建一个空字符串
String(String value)根据指定的value创建字符串
String(char[] value)根据指定的字符数组创建字符串
String(byte[] bytes)根据指定的字节数组创建字符串
class Main{
    public static void main(String[] args) {
        String str1=new String();
        String str2=new String("abcd");
        char[] charArray=new char[]{'D','E','F'};
        String str3=new String(charArray);
        byte[] arr={97,98,99};
        String str4=new String(arr);
        System.out.println("a"+str1+"b");
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
    }
}

bcac9354b9234904b13784a1b2ddd131.jpeg

二. String常用的方法

方法描述
concat()将两个字符串连接在一起
equals()比较两个字符串的值
charAt()返回存在于指定位置的字符
getBytes()将字符串转换为字节数组
indexOf()返回字符串中指定字符的位置
length()返回指定字符串的大小
replace()将指定的旧字符替换为指定的新字符
substring()返回字符串的子字符串
split()将字符串分成字符串数组
toLowerCase()将字符串转换为小写
toUpperCase()将字符串转换为大写
valueOf()返回指定数据的字符串表示形式

下面是 String 类支持的常用方法,更多详细,参看 Java API 文档:

SN(序号)方法描述
1char charAt(int index)
返回指定索引处的 char 值。
2int compareTo(Object o)
把这个字符串和另一个对象比较。
3int compareTo(String anotherString)
按字典顺序比较两个字符串。
4int compareToIgnoreCase(String str)
按字典顺序比较两个字符串,不考虑大小写。
5String concat(String str)
将指定字符串连接到此字符串的结尾。
6boolean contentEquals(StringBuffer sb)
当且仅当字符串与指定的StringButter有相同顺序的字符时候返回真。
7static String copyValueOf(char[] data)
返回指定数组中表示该字符序列的 String。
8static String copyValueOf(char[] data, int offset, int count)
返回指定数组中表示该字符序列的 String。
9boolean endsWith(String suffix)
测试此字符串是否以指定的后缀结束。
10boolean equals(Object anObject)
将此字符串与指定的对象比较。
11boolean equalsIgnoreCase(String anotherString)
将此 String 与另一个 String 比较,不考虑大小写。
12byte[] getBytes()
 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
13byte[] getBytes(String charsetName)
使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
14void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 将字符从此字符串复制到目标字符数组。
15int hashCode()
返回此字符串的哈希码。
16int indexOf(int ch)
返回指定字符在此字符串中第一次出现处的索引。
17int indexOf(int ch, int fromIndex)
返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
18int indexOf(String str)
 返回指定子字符串在此字符串中第一次出现处的索引。
19int indexOf(String str, int fromIndex)
返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
20String intern()
 返回字符串对象的规范化表示形式。
21int lastIndexOf(int ch)
 返回指定字符在此字符串中最后一次出现处的索引。
22int lastIndexOf(int ch, int fromIndex)
返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
23int lastIndexOf(String str)
返回指定子字符串在此字符串中最右边出现处的索引。
24int lastIndexOf(String str, int fromIndex)
 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。
25int length()
返回此字符串的长度。
26boolean matches(String regex)
告知此字符串是否匹配给定的正则表达式。
27boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
测试两个字符串区域是否相等。
28boolean regionMatches(int toffset, String other, int ooffset, int len)
测试两个字符串区域是否相等。
29String replace(char oldChar, char newChar)
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
30String replaceAll(String regex, String replacement
使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
31String replaceFirst(String regex, String replacement)
 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
32String[] split(String regex)
根据给定正则表达式的匹配拆分此字符串。
33String[] split(String regex, int limit)
根据匹配给定的正则表达式来拆分此字符串。
34boolean startsWith(String prefix)
测试此字符串是否以指定的前缀开始。
35boolean startsWith(String prefix, int toffset)
测试此字符串从指定索引开始的子字符串是否以指定前缀开始。
36CharSequence subSequence(int beginIndex, int endIndex)
 返回一个新的字符序列,它是此序列的一个子序列。
37String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。
38String substring(int beginIndex, int endIndex)
返回一个新字符串,它是此字符串的一个子字符串。
39char[] toCharArray()
将此字符串转换为一个新的字符数组。
40String toLowerCase()
使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
41String toLowerCase(Locale locale)
 使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。
42String toString()
 返回此对象本身(它已经是一个字符串!)。
43String toUpperCase()
使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
44String toUpperCase(Locale locale)
使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。
45String trim()
返回字符串的副本,忽略前导空白和尾部空白。
46static String valueOf(primitive data type x)
返回给定data type类型x参数的字符串表示形式。

代码 案例操作:

(1)获取字符串长度以及访问字符串中的字符

class Main{
    public static void main(String[] args) {
        String s="ababcdedcba";//定义字符串s
        //获取字符串长度
        System.out.println("length():"+s.length());
        System.out.println("字符串中第一个字符:"+s.charAt(0));
        System.out.println("字符c第一次出现的位置:"+s.indexOf('c'));
        System.out.println("字符c最后一次出现的位置:"+s.lastIndexOf('c'));
        System.out.println("子字符串ab第一次出现的位置:"+s.indexOf("ab"));
        System.out.println("子字符串最后一次出现的位置:"+s.lastIndexOf("ab"));
    }
}

(2)字符串的转换操作

class Main{
    public static void main(String[] args) {
        String str="abcd";
        System.out.print("将字符串转换为字符数组后的结果:");
        char[] charArray=str.toCharArray();
        System.out.println(charArray);
        for(int i=0;i<charArray.length;i++){
            if(i!=charArray.length-1){
                System.out.print(charArray[i]+",");
            }else{
                System.out.println(charArray[i]);
            }
        }
        System.out.println("将int值转换为String类型之后的结果:"+String.valueOf(12));
        System.out.println("将字符串转换为大写之后的结果:"+str.toUpperCase());
        System.out.println("将字符串转为小写之后的结果:"+str.toLowerCase());

    }
}

(3)字符串的替换和去空格操作

class Main{
    public static void main(String[] args){
        String s="itcast";
        System.out.println("将it替换成cn.it的结果:"+s.replace("it","cn.it"));
        String s1="   i t c a s t   ";
        System.out.println("去掉字符串两端的空格后的结果:"+s1.trim());
        System.out.println("去掉字符串中的所有空格后的结果:"+s1.replace(" ",""));

    }
}

(4)字符串判断

class Main{
    public static void main(String[] args){
        String s1="String";
        String s2="string";
        System.out.println("判断字符串s1是否以Str开头:"+s1.startsWith("Str"));
        System.out.println("判断字符串s1是否以ng结尾:"+s1.endsWith("ng"));
        System.out.println("判断字符串s1是否包含tri:"+s1.contains("tri"));
        System.out.println("判断字符串是否为空:"+s1.isEmpty());
        System.out.println("判断s1和s2的内容是否完全相同:"+s1.equals(s2));
        System.out.println("忽略大小写情况下判断s1和s2内容是否相同:"+s1.equalsIgnoreCase(s2));
        System.out.println("按照Unicode比较s1和s2的大小:"+s1.compareTo(s2));
    }
}

equals()方法用于比较两个字符串内容是否相等,==用于比较两个字符串对象的地址是否相同 

(5)字符串的截取和分割操作

class Main{
    public static void main(String[] args){
        String str="石家庄-武汉-哈尔滨";
        System.out.println("从第五个字符截取到末尾的结果:"+str.substring(4));
        System.out.println("从第五个字符截取到第六个字符的结果:"+str.substring(4,6));//注意
        System.out.print("分割后的字符串数组中的元素一次为:");
        String[] strArray=str.split("-");
        for(int i=0;i< strArray.length;i++){
            if(i!= strArray.length-1){
                System.out.print(strArray[i]+",");
            }else{
                System.out.println(strArray[i]);
            }
        }
    }
}

三.StringBuffer类

在Java中,因为String类是final类型的,所以使用String定义的字符串是一个常量,也就是说使用String定义的字符串一旦创建,其内容和长度是不可改变的.为了便于对字符串进行修改,Java提供了StringBuffer类(也成字符串缓冲区)来操作字符串.StringBuffer类和String类最大的区别在于他的内容和长度都是可以改变的.StringBuffer类就像一个字符容器,当在其中添加或删除字符时,操作的都是这个字符容器,因此并不会产生新的StringBuffer对象.

以下是 StringBuffer 类支持的主要方法:

序号方法描述
1public StringBuffer append(String s)
将指定的字符串追加到此字符序列。
2public StringBuffer reverse()
 将此字符序列用其反转形式取代。
3public delete(int start, int end)
移除此序列的子字符串中的字符。
4public insert(int offset, int i)
将 int 参数的字符串表示形式插入此序列中。
5replace(int start, int end, String str)
使用给定 String 中的字符替换此序列的子字符串中的字符。

下面的列表里的方法和 String 类的方法类似:

序号方法描述
1int capacity()
返回当前容量。
2char charAt(int index)
返回此序列中指定索引处的 char 值。
3void ensureCapacity(int minimumCapacity)
确保容量至少等于指定的最小值。
4void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
将字符从此序列复制到目标字符数组 dst
5int indexOf(String str)
返回第一次出现的指定子字符串在该字符串中的索引。
6int indexOf(String str, int fromIndex)
从指定的索引处开始,返回第一次出现的指定子字符串在该字符串中的索引。
7int lastIndexOf(String str)
返回最右边出现的指定子字符串在此字符串中的索引。
8int lastIndexOf(String str, int fromIndex)
返回最后一次出现的指定子字符串在此字符串中的索引。
9int length()
 返回长度(字符数)。
10void setCharAt(int index, char ch)
将给定索引处的字符设置为 ch
11void setLength(int newLength)
设置字符序列的长度。
12CharSequence subSequence(int start, int end)
返回一个新的字符序列,该字符序列是此序列的子序列。
13String substring(int start)
返回一个新的 String,它包含此字符序列当前所包含的字符子序列。
14String substring(int start, int end)
返回一个新的 String,它包含此序列当前所包含的字符子序列。
15String toString()
返回此序列中数据的字符串表示形式。

class Main{
    public static void main(String[] args){
        System.out.println("1.添加--------------------------");
        add();
        System.out.println("2.删除--------------------------");
        remove();
        System.out.println("3.修改--------------------------");
        alter();
        System.out.println("4.截取--------------------------");
        sub();
    }
    public static void add(){
        StringBuffer sb=new StringBuffer();
        sb.append("abcdefg");
        sb.append("hij").append("klmn");
        System.out.println("append添加结果:"+sb);
        sb.insert(2,"123");
        System.out.println("insert添加结果:"+sb);//指定下标下插入后的结果
    }
    public static void remove(){
        StringBuffer sb=new StringBuffer();
        sb.append("abcdefg");
        sb.delete(1,5);
        System.out.println("删除指定范围结果:"+sb);
        sb.deleteCharAt(2);
        System.out.println("删除指定位置结果:"+sb);
        sb.delete(0,sb.length());
        System.out.println("清空缓冲区结果:"+sb);

    }
    public static void alter(){
        StringBuffer sb=new StringBuffer("abcdefg");
        sb.setCharAt(1,'p');
        System.out.println("修改指定位置字符结果:"+sb);
        sb.replace(1,3,"qq");
        System.out.println("替换指定位置字符(串)结果:"+sb);
        System.out.println("字符串翻转结果:"+sb.reverse());
    }
    public static void sub(){
        StringBuffer sb=new StringBuffer();
        System.out.println("获取sb的初始容量:"+sb.capacity());
        sb.append("itcast123");
        System.out.println("append添加结果:"+sb);
        System.out.println("截取第七道第九个字符:"+sb.substring(6,9));
    }
}

四.StringBuilder类、StringBuffer类和String类区别

StringBuilder类与StringBuffer类的功能相似,且两个类中提供的方法也基本相同.二者最大的不同在于Stringbuffer类的方法是线程安全的,而StringBuilder类没有实现线程安全功能,所以性能略高.通常情况下,如果创建一个内容可变的字符串对象,应该优先考虑使用StringBuilder类.

StringBuilder类同样提供了一系列添加(append)、插入(insert)、替换(replace)、和删除(delete)等方法。

StringBuilder类、StringBuffer类和String类有很多相似之处,初学者在使用时很容易混淆。一下三个类对比:

(1)String类表示的字符串是常量,一旦创建后,内容和长度都是无法修改的。而StringBuilder类、StringBuffer类表示字符容器,其内容和长度可以随时修改。在操作字符串时如果该字符串仅用于表示数据类型,则使用String类即可;但是如果需要对字符串中的字符进行增删操作,则使用StringBuffer类和StringBuilder类。如果有大量字符串拼接操作,并不要求线程安全,则使用StringBuilder类更高效。

(2)对于equls()方法的使用前面已经介绍了,但是StringBuffer类与StringBuilder类并没有重写Object类的equals()方法,也就是说equals()方法对于这两个类并不起作用。

(3)String类对象可以用+进行连接,而StringBuilder类和StringBuffer类的对象则不能。

  • 49
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值