Java库中提供了String类,给出你自己对下面方法的实现(将新类命名为MyString1)

public MyString1(char[] chars);
public char charAt(int index);
public int length();
public MyString1 substring(int begin, int end);
public MyString1 toLowerCase();
public boolean equals(MyString1 s);
public static MyString1 valueOf(int i);

MyString1类

public class MyString1 {//MyString类的实现
	private final char[] chars;
	public char[] show() {
		return chars;
	}
	public MyString1(char[] chars) {
		this.chars=chars;
	}
	public char charAt(int index) {
		return this.chars[index-1];
	}
	public int length() {
		return chars.length;
	}
	public MyString1 substring(int begin, int end) {
		char[] string=new char[end-begin+1];
		int i=0;
		int n=0; 
		for(i=begin;i<end;i++){
			string[n]=chars[i];
			n++;
		}
		MyString1 newString=new MyString1(string);
		return newString;
	}
	public MyString1 toLowerCase() {
		char[] string = new char[chars.length];
		for(int i=0; i<chars.length; i++) {
			string[i]=chars[i];
		}
		for(int i=0; i<chars.length; i++) {
			if(string[i]>='A'&&string[i]<='Z') {
				string[i]=(char) (string[i]+32);
			}
		}
		MyString1 newString=new MyString1(string);
		return newString;
	}
	public boolean equals(MyString1 s) {
		int flag=0;
		if(this.chars.length==s.chars.length) {
			for(int i=0; i<=chars.length-1; i++) {
				if(s.chars[i]!=this.chars[i]) {
					flag=1;
					break;
				}
			}
			if(flag==0)
				return true;
			else
				return false;
		}
		return false;
	}
	public static MyString1 valueOf(int i) {
		char[] string=new char[10];
		int flag=0;
		for(int n=0; i*10/10!=0; n++) {
			string[n]=(char)(i%10+(int)'0');
			i=i/10;
			flag++;
		}
		int top=0,end=flag-1;	
		while(top<end){
			char temp=string[top];
			string[top]=string[end];
			string[end]=temp;
			top++;
			end--;
		}
		MyString1 newString=new MyString1(string);
		return newString;
	}
}

测试程序:

public class homeWork3 {//测试程序
	public static void main(String[] args) {
		char[] s1 = new char[]{'J','a','v','a',' ','T','e','x','t'};
		char[] s2 = new char[]{'S','t','r','i','n','g'};
		MyString1 string1 = new MyString1(s1);
		MyString1 string2 = new MyString1(s2);
		System.out.println(string1.show());
		System.out.println(string1.charAt(2));
		System.out.println(string1.length());
		System.out.println((string1.substring(0, 3)).show());
		System.out.println(string1.toLowerCase().show());
		System.out.println(string1.equals(string2));
		System.out.println(MyString1.valueOf(1234567).show());
	}
}

运行截图:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值