Strings
要用数组的思想来理解String
与数组声明方法类似,也与类的实例化思想相同
The String object is immutable, meaning once a String object is created, its value cannot be lengthened or shortened; none of the characters canchange .
当两个String直接用+相连:
如果像计算相加的结果,需要加()
String Methods
String concat(String s)
Concatenates the specified strings to the end of this string. Same as +.
Output:
int length()
– Returns the length of the string;
用法就是数组的:数组名.length 返回元素个数int
char charAt(int index)
– returns the specifed character at the position of index in the String
返回该数组的第 index+1个元素
返回
String toUpperCase()
– returns a new string by converting all of the characters in this string to uppercase
String toLowerCase()
– returns a new string by converting all of thecharacters in this string to lowercase
String substring(int begin, int end)
- returns a String from this string using characters between the indices begin (inclusive) and end
(exclusive)
String substring(int begin)
– returns a String from this string from the beginning index to the end.
注意index起始为0,因为这是数组。所以indx是指第index+1个元素
String replace(char oldChar, char newChar)
- Returns a string resulting from replacing all occurrences of oldChar in this string with
newChar
新的替换旧的
int compareTo(String s)
– Compares this String with thep arameter String s - returns an int <0 if this String precedes the argument String s, an int >0 if this String follows the argument String s, otherwise an int =0 if they are equal
安照ASCII表的顺序,从左向右一个个比较。
boolean equals (Object s)
– returns true if this String should be considered the same as the parameter object s, which could be another String
boolean equalsIgnoreCase (String s)
– compares this string to another String ignoring case Considerations returning true if they should be considered equal.
同长度,同一个char(不区分大小写) 则为true
按照数组的思想,以下s1和s2
s1==s2为假,因为两个Hello是在不同的堆里面,此时比较的是s1和s2分别储存的地址(用上面的method比较才会为真)
如果是以以下形式
s1==s2为真,因为此时比较的是它们的值