java学习第19天,字符串截取

字符串的操作是写代码的基础,这里很重要多看看

package java11to20;

public class D19_MyString {
	public static final int max = 20;
	int length;
	char[] data;

	public static void main(String[] args) {
		D19_MyString firstStr = new D19_MyString("I love you forever.");
		D19_MyString secondStr = new D19_MyString("you");
		int position = firstStr.locate(secondStr);
		System.out.println(String.format("%s 字段是在 %s 的第%s个位置", secondStr, firstStr, position));

		D19_MyString thirdStr = new D19_MyString("ki");
		position = firstStr.locate(thirdStr);
		System.out.println(String.format("%s 字段是在 %s 的第%s个位置", secondStr, firstStr, position));

		thirdStr = firstStr.substring(1, 4);
		System.out.println(String.format("所截取的字段是:%s", thirdStr));

		thirdStr = firstStr.substring(11, 8);
		System.out.println(String.format("所截取的字段是:%s", thirdStr));
	}

	public D19_MyString() {
		length = 0;
		data = new char[max];
	}

	public D19_MyString(String par) {
		data = new char[max];
		length = par.length();
		for (int i = 0; i < length; i++) {
			data[i] = par.charAt(i);
		}
	}

	public String toString() {
		String result = "";
		for (int i = 0; i < length; i++) {
			result += data[i];
		}
		return result;
	}

	public int locate(D19_MyString myString) {
		boolean match = false;
		for (int i = 0; i < length - myString.length + 1; i++) {
			match = true;
			for (int j = 0; j < myString.length; j++) {
				if (data[i + j] != myString.data[j]) {
					match = false;
					break;
				}
			}
			if (match) {
				return i;
			}
		}
		return -1;
	}

	public D19_MyString substring(int startPosition, int parlength) {
		if (startPosition + parlength > max) {
			System.out.println("溢出");
			return null;
		}
		D19_MyString result = new D19_MyString();
		result.length = parlength;
		for (int i = 0; i < parlength; i++) {
			result.data[i] = data[startPosition + i];
		}
		return result;
	}
}

输出结果:

you 字段是在 I love you forever. 的第7个位置
you 字段是在 I love you forever. 的第-1个位置
所截取的字段是: lov
所截取的字段是:forever.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值