packagecn.tedu.api;importjava.util.Arrays;//本类用于练习String类的常用方法publicclassTestString2{publicstaticvoidmain(String[] args){//1.创建字符串String s ="abc";char[] value ={'a','b','c'};String ss =newString(value);//2.测试常用方法/* charAt 获取指定下标处的字符*/System.out.println(s.charAt(1));/* concat 用于拼接指定的字符串,但注意,不会改变原串,而是重新建一个新串存放*/String s2 = s.concat("cxy");System.out.println(s);//abcSystem.out.println(s2);//abccxy/* */System.out.println(s.concat("cxy"));//abccxySystem.out.println(s.endsWith("y"));//falseSystem.out.println(s.startsWith("a"));//trueSystem.out.println(s == ss);//falseSystem.out.println(s.equals(ss));//true//获取指定元素首次出现的下标值System.out.println(ss.indexOf("b"));//1
ss ="abcbb";//获取指定元素最后一次出现的下标值System.out.println(ss.lastIndexOf("b"));//4//获取指定字符串的长度(和数组的不同,数组没有(),数组是属性,这个是方法)System.out.println(ss.length());//5String s3 ="a b c d e";// split 根据指定规则分割字符串,主要返回值类型为String[]// 需要使用Arrays.toString数组工具类方法来打印System.out.println(s3.split(" "));System.out.println(Arrays.toString(s3.split(" ")));// substring 从指定位置截取子串,如果只有一个下标,那就从指定位置开始截取,包含指定位置// 如果有两个下标,截取两个下标之间的部分,左闭右开System.out.println(s3.substring(3));// c d e------[3,结束]System.out.println(s3.substring(1,5));// b c-----[1,5)//转为全大写和全小写System.out.println(s3.toUpperCase());//A B C D ESystem.out.println(s3.toLowerCase());//a b c d e
s3 =" abcde ";//返回一个副本,去除首尾空格System.out.println(s3.trim());//abcde// 把其他类型的值 转为 StringSystem.out.println("20"+10);//2010System.out.println(String.valueOf(10));//10System.out.println(String.valueOf(80)+10);//8010System.out.println(10+10);//20}}
7. 常用方法摘抄
char | charAt(int index):获取指定下标处的字符
int | compareTo(String anotherString):按字典序比较两个字符串(比较是基于字符串中每个字符的Unicode值。)
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/publicbooleanequals(Object anObject){if(this== anObject){returntrue;}if(anObject instanceofString){String anotherString =(String)anObject;int n = value.length;if(n == anotherString.value.length){char v1[]= value;char v2[]= anotherString.value;int i =0;while(n--!=0){if(v1[i]!= v2[i])returnfalse;
i++;}returntrue;}}returnfalse;}
publicfinalclassStringimplementsjava.io.Serializable,Comparable<String>,CharSequence{/** The value is used for character storage. */privatefinalchar value[];/**
* Initializes a newly created {@code String} object so that it represents
* the same sequence of characters as the argument; in other words, the
* newly created string is a copy of the argument string. Unless an
* explicit copy of {@code original} is needed, use of this constructor is
* unnecessary since Strings are immutable.
*
* @param original
* A {@code String}
*/publicString(String original){this.value = original.value;this.hash = original.hash;}
/**
* Constructs a string buffer with no characters in it and an
* initial capacity of 16 characters.
*/publicStringBuffer(){super(16);}
扩容机制
/**
* Ensures that the capacity is at least equal to the specified minimum.
* If the current capacity is less than the argument, then a new internal
* array is allocated with greater capacity. The new capacity is the
* larger of:
* <ul>
* <li>The {@code minimumCapacity} argument.
* <li>Twice the old capacity, plus {@code 2}.
* </ul>
* If the {@code minimumCapacity} argument is nonpositive, this
* method takes no action and simply returns.
* Note that subsequent operations on this object can reduce the
* actual capacity below that requested here.
*
* @param minimumCapacity the minimum desired capacity.
*/publicvoidensureCapacity(int minimumCapacity){if(minimumCapacity >0)ensureCapacityInternal(minimumCapacity);}/**
* For positive values of {@code minimumCapacity}, this method
* behaves like {@code ensureCapacity}, however it is never
* synchronized.
* If {@code minimumCapacity} is non positive due to numeric
* overflow, this method throws {@code OutOfMemoryError}.
*/privatevoidensureCapacityInternal(int minimumCapacity){// overflow-conscious code/*若所需长度大于已有长度,才继续进行扩容*/if(minimumCapacity - value.length >0){/*通过Arrays.copyOf(),将旧value数组内容先复制到newCapacity大小的数组,再赋值给新value*/
value =Arrays.copyOf(value,newCapacity(minimumCapacity));}}/**
* The maximum size of array to allocate (unless necessary).
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/privatestaticfinalint MAX_ARRAY_SIZE =Integer.MAX_VALUE -8;/**
* Returns a capacity at least as large as the given minimum capacity.
* Returns the current capacity increased by the same amount + 2 if
* that suffices.
* Will not return a capacity greater than {@code MAX_ARRAY_SIZE}
* unless the given minimum capacity is greater than that.
*
* @param minCapacity the desired minimum capacity
* @throws OutOfMemoryError if minCapacity is less than zero or
* greater than Integer.MAX_VALUE
*/privateintnewCapacity(int minCapacity){// overflow-conscious code/*默认扩容:newCapacity = 两倍的原长度 + 2*/int newCapacity =(value.length <<1)+2;if(newCapacity - minCapacity <0){/*默认扩容后还是小于所需长度*/
newCapacity = minCapacity;/*直接补充至所需长度*/}return(newCapacity <=0|| MAX_ARRAY_SIZE - newCapacity <0)?hugeCapacity(minCapacity): newCapacity;}privateinthugeCapacity(int minCapacity){/*大小超出Integer范围爆异常*/if(Integer.MAX_VALUE - minCapacity <0){// overflowthrownewOutOfMemoryError();}/*返回minCapacity与MAX_ARRAY_SIZE最大值*/return(minCapacity > MAX_ARRAY_SIZE)? minCapacity : MAX_ARRAY_SIZE;}