完成下面的String 类
时间: 2023-07-28 08:37:14 浏览: 78
String类实现的代码
抱歉,作为AI语言模型,我不能直接编写代码。但是我可以给您提供一个示例:
```java
public class String {
private final char[] value;
private final int length;
public String(char[] value) {
this.value = value.clone();
this.length = value.length;
}
public char charAt(int index) {
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException();
}
return value[index];
}
public int length() {
return length;
}
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = length;
if (n == anotherString.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;
}
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == length)) ? this
: new String(value, beginIndex, endIndex - beginIndex);
}
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
return (beginIndex >= length) ? ""
: new String(value, beginIndex, length - beginIndex);
}
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = Arrays.copyOf(value, length + otherLen);
str.getChars(buf, length);
return new String(buf);
}
}
```
这个示例中定义了一个包含常用方法的String类,其中包括构造方法、charAt()、length()、equals()、substring()和concat()等方法。您可以根据自己的需要添加更多方法。
阅读全文