Bootstrap

Java、实现String类

在这里插入图片描述

 


package pack2;

import java.util.ArrayList;

public class MyString1 {
	private ArrayList<Character> list = new ArrayList<>();	//数组列表

	/**指定字符数组的构造方法*/
	public MyString1(char[] chars) {
		for (char c : chars) 
			list.add(c);
	}
	
	/**返回指定下标元素*/
	public char charAt(int index) {
		return list.get(index);
	}
	
	/**返回长度*/
	public int length() {
		return list.size();
	}
	
	/**返回 begin 到 end - 1 的子串*/
	public MyString1 substring(int begin, int end) {
		char[] temp = new char[end - begin];
		
		for (int i = begin; i < end; i++) 
			temp[i - begin] = list.get(i);
		return new MyString1(temp);
	}
	
	/**返回小写的形式*/
	public MyString1 toLowerCase() {
		char[] temp = new char[list.size()];
		
		for (int i = 0; i < length(); i++) 
			temp[i] = Character.toLowerCase(list.get(i));
		return new MyString1(temp);
	}
	
	/**是否等于指定串?*/
	public boolean equals(MyString1 s) {
		if(length() != s.length()) return false;
		
		for (int i = 0; i < length(); i++) 
			if(charAt(i) != s.charAt(i))
				return false;
		return true;
	}
	
	/**将整型值转换为MyString1的静态方法*/
	public static MyString1 valueOf(int b) {
		return new MyString1(String.valueOf(b).toCharArray());
	}
	
	@Override
	public String toString() {
		StringBuffer stringBuffer = new StringBuffer(list.size());
		
		for (Character character : list) 
			stringBuffer.append(character);
		return stringBuffer.toString();
	}
	
//————————————————————————————————————————————————————————————————
	public static void main(String[] args) {
		MyString1 myString1 = new MyString1(new char[] {'I', 'o'});
		System.out.println(myString1.charAt(0));
		System.out.println(myString1.equals(new MyString1(new char[] {'i'})));
		System.out.println(myString1.toLowerCase());
		System.out.println(myString1.length());
		System.out.println(myString1.substring(0, myString1.length()));
	}
}

 

;