String类练习题

1. 编写一个方法,将一段文本中的各个单词的字母顺序翻转,
   例如:“To be or not to be",将变成"oT eb ro ton ot eb"。
2. String s=”name=zhangsan age=18 classNo=090728”;
   将上面的字符串中包含的信息存放到Student(里面有name,age,classNo三个属性)的对象中:
3. 上网查询 instanceof 这个关键字的用法,并用用代码演示
4.自己写代码实现String类中的charAt方法和indexOf方法,不允许使用String中的方法实现
5.自己写代码实现String类中的contains方法,不允许使用String中的方法实现

 

package Demo7;

class Demo {

}

public class Demo7 extends Demo {

	public static void test1() {
		String str = "To be or not to be";
		String s = "";
		String[] strs = str.split(" ");
		for (int i = 0; i < strs.length; i++) {
			char[] ch = strs[i].toCharArray();
			for (int j = 0; j < ch.length / 2; j++) {
				char temp = ch[j];
				ch[j] = ch[ch.length - 1 - j];
				ch[ch.length - 1 - j] = temp;
			}
			strs[i] = String.valueOf(ch);
			s += strs[i] + " ";
		}

		System.out.println("第一题:" + s);
	}

	public static void test2() {
		Student student = new Student();
		String str = " name=zhangsan age=18 classNo=090728";
		String[] strs = str.trim().split(" ");
		for (int i = 0; i < strs.length; i++) {
			strs[i] = strs[i].substring((strs[i].indexOf("=")) + 1);

		}
		student.setName(strs[0]);
		student.setAge(strs[1]);
		student.setClassNo(strs[2]);
		System.out.println("第二题:" + student);
	}

	public static boolean test3() {
		Demo demo1 = new Demo(); // 父类
		Demo7 demo2 = new Demo7(); // 子类
		return demo2 instanceof Demo;
	}

	public static char test4_charAt(String str, int index) throws ArrayIndexOutOfBoundsException {
		char[] ch = str.toCharArray();
		if (index > ch.length - 1 || index < 0) {
			throw new ArrayIndexOutOfBoundsException();
		}
		for (int i = 0; i < ch.length; i++) {
			if (i == index) {
				return ch[i];
			}
		}
		return 0;

	}

	public static int test4_indexOf(String str, String str1) {
		String[] strs = str.split("");
		for (int i = 0; i < strs.length; i++) {
			if (str1.equals(strs[i])) {
				return i;
			}
		}
		return -1;
	}

	public static boolean test5_contains(String str, String str1) {
		String[] strs = str.split("");
		for (int i = 0; i < strs.length - str1.length() + 1; i++) {
			String s = "";
			for (int j = i; j < str1.length() + i; j++) {
				s += strs[j];
			}
			if(str1.equals(s)) {
				return true;
			}
		}
		return false;
	}

	public static void main(String[] args) {

		test1();
		test2();
		System.out.println("第三题:" + test3());
		try {
			System.out.println("第四题的charAt方法:" + test4_charAt("abcde", 3));
		} catch (ArrayIndexOutOfBoundsException e) {
			System.err.println("数组下标越界!");
		}
		System.out.println("第四题的indexOf方法:" + test4_indexOf("abcde", "c"));

		System.out.println("第五题:" + test5_contains("abcde", "ae"));
	}

}


 

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值