String类的常用方法
String类对象保存不可修改的Unicode字符序列
String类的下述方法能创建并返回一个新的String对象:concat,replace,substring,toLowerCase,toUppercase,trim.
提供查找功能的有关方法:endsWith,startsWith,indexOf,lastIndexOf.
Java字符串类的常用方法https://blog.csdn.net/pmcasp/article/details/78735860
提供比较功能的方法:equals,equalslgnoreCase,compareTo.
其他方法:charAt,length.
public static String valueOf(......)可以将基本类型数据转换为字符串。
方法 |
中文和英文解释 |
源代码和解释 |
length() |
Returns the length of this string. 返回字符串的长度 |
public int length() { return value.length; //返回字符数组的长度 } |
String类的JDK源码分析:
public final class String {
/** The value is used for character storage. */
private final char value[]; //声明一个char类型的常量value【char[] value】
public String() {
this.value = new char[0]; //初始化value,使用方法例如:String a = new String();
}
public String(String original) {
this.value = original.value; //使用方法例如:String a = new String("123");
}
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
public int length() {
return value.length;
}
public boolean isEmpty() {
return value.length == 0;
}
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
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])
return false;
i++;
}
return true;
}
}
return false;
}
//其余方法省略。大家把如上列出的方法读懂,应该就完全理解了String类的核心了,而且通过String类的学习也掌握了数组的基本应用
}
----
String gh="a"; //一个对象
String gh = new String("a"); //两个个对象分别是gh和“a”
for (int i = 0; i < 1000; i++) { //一千个对象
gh = gh + i;
}
System.out.println(gh);
----