Java String StringBuffer StringBuilder

一、综述

Java中涉及到字符串的操作时无疑会想到String、StringBuffer、StringBuilder。其中String是不可变类,声明时候就不可改变,改变的只是内存地址的引用。StringBuffer和StringBuilder的内容是可以改变的,只是StringBuilder是线程公布的,StringBuffer操作字符串时效率较高些。

二、String

String可使用“+”拼接字符串,但是可能引发每次创建一个String类(看字符串池中是否已经有内容相同的字符串)。

修饰符与类型方法与描述
charcharAt(int index)
Returns the char value at the specified index.
intcodePointAt(int index)
Returns the character (Unicode code point) at the specified index.
intcodePointBefore(int index)
Returns the character (Unicode code point) before the specified index.
intcodePointCount(int beginIndex, int endIndex)
Returns the number of Unicode code points in the specified text range of this String.
intcompareTo(String anotherString)
Compares two strings lexicographically.
intcompareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
Stringconcat(String str)
Concatenates the specified string to the end of this string.
booleancontains(CharSequence s)
Returns true if and only if this string contains the specified sequence of char values.
booleancontentEquals(CharSequence cs)
Compares this string to the specified CharSequence.
booleancontentEquals(StringBuffer sb)
Compares this string to the specified StringBuffer.
static StringcopyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
static StringcopyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
booleanendsWith(String suffix)
Tests if this string ends with the specified suffix.
booleanequals(Object anObject)
Compares this string to the specified object.
booleanequalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
static Stringformat(Locale l, String format, Object... args)
Returns a formatted string using the specified locale, format string, and arguments.
static Stringformat(String format, Object... args)
Returns a formatted string using the specified format string and arguments.
byte[]getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
byte[]getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
voidgetBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated. 
This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset.
byte[]getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
voidgetChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
inthashCode()
Returns a hash code for this string.
intindexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
intindexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
intindexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
intindexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
Stringintern()
Returns a canonical representation for the string object.
booleanisEmpty()
Returns true if, and only if, length() is 0.
intlastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
intlastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
intlastIndexOf(String str)
Returns the index within this string of the last occurrence of the specified substring.
intlastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
intlength()
Returns the length of this string.
booleanmatches(String regex)
Tells whether or not this string matches the given regular expression.
intoffsetByCodePoints(int index, int codePointOffset)
Returns the index within this String that is offset from the given index by codePointOffset code points.
booleanregionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
booleanregionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
Stringreplace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
Stringreplace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
StringreplaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
StringreplaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
String[]split(String regex)
Splits this string around matches of the given regular expression.
String[]split(String regex, int limit)
Splits this string around matches of the given regular expression.
booleanstartsWith(String prefix)
Tests if this string starts with the specified prefix.
booleanstartsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with the specified prefix.
CharSequencesubSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
Stringsubstring(int beginIndex)
Returns a new string that is a substring of this string.
Stringsubstring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
char[]toCharArray()
Converts this string to a new character array.
StringtoLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
StringtoLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
StringtoString()
This object (which is already a string!) is itself returned.
StringtoUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
StringtoUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
Stringtrim()
Returns a copy of the string, with leading and trailing whitespace omitted.
static StringvalueOf(boolean b)
Returns the string representation of the boolean argument.
static StringvalueOf(char c)
Returns the string representation of the char argument.
static StringvalueOf(char[] data)
Returns the string representation of the char array argument.
static StringvalueOf(char[] data, int offset, int count)
Returns the string representation of a specific subarray of the char array argument.
static StringvalueOf(double d)
Returns the string representation of the double argument.
static StringvalueOf(float f)
Returns the string representation of the float argument.
static StringvalueOf(int i)
Returns the string representation of the int argument.
static StringvalueOf(long l)
Returns the string representation of the long argument.
static StringvalueOf(Object obj)
Returns the string representation of the Object argument
部分重要方法代码如下:

// TODO Auto-generated method stub
		String str = "123abcd4$!@#$";
		String str1= "ac45%";
		String str2="123abcd4$!@#$";
		
		System.out.println(str.indexOf("c")); //5
		char someIndexStr = str.charAt(5);
		System.out.println(someIndexStr);  //输出:c
		
		System.out.println(str.compareTo(str1)); //-48
		System.out.println(str.compareTo(str2));//0
		
		String str3="123ABCD4$!@#$";
		System.out.println(str.compareTo(str3));
		System.out.println(str.compareToIgnoreCase(str3)); //0
		
		System.out.println(str.concat(str1)); //23abcd4$!@#$ac45%
		System.out.println(str.contains("abc")); //true
		System.out.println(str.contains("13")); //false
		System.out.println(str.endsWith("#$")); //true
		System.out.println(str.startsWith("1"));//true
		String str4="acaa";
		System.out.println(str4.lastIndexOf("a")); //3
		
		System.out.println(str4.length());//4
		System.out.println(str4.replace("a", "&"));//&c&&
		System.out.println(str4.replaceFirst("a", "&"));//&caa
		
		
		/*
		 * 1
         *c4d
         *de8
         *  9
		 */
		String str5="1ac4dade8a9";
		String[] strArray = str5.split("a");
		System.out.println("字符串分割:");
		for(String strTemp:strArray)
		{
     			System.out.println(strTemp);
		}

		String str6 = "1234567";
		System.out.println(str6.substring(1, str6.length())); //234567
        char[] charArray = str6.toCharArray();
        System.out.println("转换成字符数组:");
        for(char temp:charArray)
        {
        	System.out.println(temp);
        }
        
        System.out.println(str4.toUpperCase());//ACAA
        String str7="a d ccc gg ";
        System.out.println(str7.trim());//a d ccc gg
        str7.replace("a", "h");
        System.out.println(str7);//a d ccc gg 
		

三‘、StringBuffer和StringBuilde:不会每次生产新的对象,而是在原有基础上进行操作,可以改变。效率较高。

以StringBufferAPI为例:

修饰符与类型方法与描述
StringBufferappend(boolean b)
Appends the string representation of the boolean argument to the sequence.
StringBufferappend(char c)
Appends the string representation of the char argument to this sequence.
StringBufferappend(char[] str)
Appends the string representation of the char array argument to this sequence.
StringBufferappend(char[] str, int offset, int len)
Appends the string representation of a subarray of the char array argument to this sequence.
StringBufferappend(CharSequence s)
Appends the specified CharSequence to this sequence.
StringBufferappend(CharSequence s, int start, int end)
Appends a subsequence of the specified CharSequence to this sequence.
StringBufferappend(double d)
Appends the string representation of the double argument to this sequence.
StringBufferappend(float f)
Appends the string representation of the float argument to this sequence.
StringBufferappend(int i)
Appends the string representation of the int argument to this sequence.
StringBufferappend(long lng)
Appends the string representation of the long argument to this sequence.
StringBufferappend(Object obj)
Appends the string representation of the Object argument.
StringBufferappend(String str)
Appends the specified string to this character sequence.
StringBufferappend(StringBuffer sb)
Appends the specified StringBuffer to this sequence.
StringBufferappendCodePoint(int codePoint)
Appends the string representation of the codePoint argument to this sequence.
intcapacity()
Returns the current capacity.
charcharAt(int index)
Returns the char value in this sequence at the specified index.
intcodePointAt(int index)
Returns the character (Unicode code point) at the specified index.
intcodePointBefore(int index)
Returns the character (Unicode code point) before the specified index.
intcodePointCount(int beginIndex, int endIndex)
Returns the number of Unicode code points in the specified text range of this sequence.
StringBufferdelete(int start, int end)
Removes the characters in a substring of this sequence.
StringBufferdeleteCharAt(int index)
Removes the char at the specified position in this sequence.
voidensureCapacity(int minimumCapacity)
Ensures that the capacity is at least equal to the specified minimum.
voidgetChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.
intindexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
intindexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
StringBufferinsert(int offset, boolean b)
Inserts the string representation of the boolean argument into this sequence.
StringBufferinsert(int offset, char c)
Inserts the string representation of the char argument into this sequence.
StringBufferinsert(int offset, char[] str)
Inserts the string representation of the char array argument into this sequence.
StringBufferinsert(int index, char[] str, int offset, int len)
Inserts the string representation of a subarray of the str array argument into this sequence.
StringBufferinsert(int dstOffset, CharSequence s)
Inserts the specified CharSequence into this sequence.
StringBufferinsert(int dstOffset, CharSequence s, int start, int end)
Inserts a subsequence of the specified CharSequence into this sequence.
StringBufferinsert(int offset, double d)
Inserts the string representation of the double argument into this sequence.
StringBufferinsert(int offset, float f)
Inserts the string representation of the float argument into this sequence.
StringBufferinsert(int offset, int i)
Inserts the string representation of the second int argument into this sequence.
StringBufferinsert(int offset, long l)
Inserts the string representation of the long argument into this sequence.
StringBufferinsert(int offset, Object obj)
Inserts the string representation of the Object argument into this character sequence.
StringBufferinsert(int offset, String str)
Inserts the string into this character sequence.
intlastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
intlastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring.
intlength()
Returns the length (character count).
intoffsetByCodePoints(int index, int codePointOffset)
Returns the index within this sequence that is offset from the given index by codePointOffset code points.
StringBufferreplace(int start, int end, String str)
Replaces the characters in a substring of this sequence with characters in the specified String.
StringBufferreverse()
Causes this character sequence to be replaced by the reverse of the sequence.
voidsetCharAt(int index, char ch)
The character at the specified index is set to ch.
voidsetLength(int newLength)
Sets the length of the character sequence.
CharSequencesubSequence(int start, int end)
Returns a new character sequence that is a subsequence of this sequence.
Stringsubstring(int start)
Returns a new String that contains a subsequence of characters currently contained in this character sequence.
Stringsubstring(int start, int end)
Returns a new String that contains a subsequence of characters currently contained in this sequence.
StringtoString()
Returns a string representing the data in this sequence.
voidtrimToSize()
Attempts to reduce storage used for the character sequence.

StringBuffer sb  = new StringBuffer("abcdef");
        sb.append("g");
        System.out.println(sb); //abcdefg
        sb.deleteCharAt(0); 
        System.out.println(sb);//bcdefg
        System.out.println(sb.insert(0, 'G')); //Gbcdefg
        System.out.println(sb.reverse());
        System.out.println(sb.indexOf("gfe")); //0



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值