实现 String类)在Java库中提供了String类,给出你自己对下面方法的实现(将新类 命名为MyString2): public MyString2(String s);public int compare(String s); public MyString2 substring(int begin);public MyString2 toUpperCaseO;public char[]toChars(); public static MyString2 valueOf(boolean b);并能够运行
时间: 2024-01-09 08:03:38 浏览: 82
以下是MyString2类的实现:
```java
public class MyString2 {
private char[] chars;
public MyString2(String s) {
this.chars = s.toCharArray();
}
public int compare(String s) {
char[] otherChars = s.toCharArray();
int len = Math.min(chars.length, otherChars.length);
for (int i = 0; i < len; i++) {
if (chars[i] != otherChars[i]) {
return chars[i] - otherChars[i];
}
}
return chars.length - otherChars.length;
}
public MyString2 substring(int begin) {
if (begin < 0 || begin >= chars.length) {
throw new IndexOutOfBoundsException();
}
char[] newChars = new char[chars.length - begin];
System.arraycopy(chars, begin, newChars, 0, newChars.length);
return new MyString2(new String(newChars));
}
public MyString2 toUpperCase() {
char[] newChars = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
if (chars[i] >= 'a' && chars[i] <= 'z') {
newChars[i] = (char) (chars[i] - 'a' + 'A');
} else {
newChars[i] = chars[i];
}
}
return new MyString2(new String(newChars));
}
public char[] toChars() {
char[] newChars = new char[chars.length];
System.arraycopy(chars, 0, newChars, 0, chars.length);
return newChars;
}
public static MyString2 valueOf(boolean b) {
return b ? new MyString2("true") : new MyString2("false");
}
}
```
以下是测试代码:
```java
public class Main {
public static void main(String[] args) {
MyString2 s = new MyString2("hello");
System.out.println(s.compare("world")); // -15
System.out.println(s.compare("help")); // 7
System.out.println(s.substring(1).toChars()); // "ello"
System.out.println(s.toUpperCase().toChars()); // "HELLO"
System.out.println(MyString2.valueOf(true).toChars()); // "true"
}
}
```
输出结果:
```
-15
7
ello
HELLO
true
```
阅读全文