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

2021/6/9 1:20:53

本文主要是介绍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.


这篇关于java学习第19天,字符串截取的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程