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.
上一篇:014信息文档管理与配置管理


下一篇:JAVA基础学习博客014