简单的字符串匹配算法,输入子串(模式串),求其在主串中的位置。一旦发现这个子串的字符不匹配,只能转而从主串的下一个来匹配。
先进行字符串的定义并进行初始化
public static final int MAX_LENGTH = 10;//定义字符串最大长度
int length;//定义字符串的实际长度
char[] data;//字符串的值
//初始化定义一个空的字符串
public MyString() {
length = 0;
data = new char[MAX_LENGTH];
}
public MyString(String paraString) {
data = new char[MAX_LENGTH];
length = paraString.length();//字符串的长度
//复制数据
for (int i = 0; i < length; i++) {
data[i] = paraString.charAt(i);
}
}
重写公共子类toString
//重写公共类中的方法
public String toString() {
String resultString = "";
for (int i = 0; i < length; i++) {
resultString += data[i];
}
return resultString;
}
1.定位子串在主串内的位置
利用tempMatch来标记是否完成匹配,如果ture表示匹配成功,如果是false表示匹配失败。默认情况下为false,当主串和子串匹配时,将tempMatch为ture,否则标记为false。
暴力匹配,先读取主串第一个字符,和子串第一个字符进行比较,若成功,就比较下一个;不成功,继续读取主串第二个字符,然后再和子串第一个字符进行比较......以此类推,直至全部匹配成功。
//定位字符在字符串内部的位置
public int locate(MyString paraMyString) {
boolean tempMatch = false;
for (int i = 0; i < length - paraMyString.length + 1; i++) {
//初始化
tempMatch = true;
for (int j = 0; j < paraMyString.length; j++) {
if (data[i + j] != paraMyString.data[j]) {
tempMatch = false;
break;
} //对子串进行匹配
}
if (tempMatch) {
return i;
} // 返回匹配位置
}
return -1;
}
2.输入数值返回在主串中对应位置的子串
输入第几个元素,在主串中查找返回其值,返回值存在新定义的reasultMyString中。先检查是否越界。再在主串中进行查找(利用for循环),返回对应值。
public MyString substring(int paraStartPosition, int paraLength) {
if (paraStartPosition + paraLength > length) {
System.out.println("The bound is exceeded.");
return null;
} //检查是否越界
MyString resultMyString = new MyString();//定义返回值子串
resultMyString.length = paraLength;//定义子串长度
for (int i = 0; i < paraLength; i++) {
resultMyString.data[i] = data[paraStartPosition + i];
} // 赋值给返回值
return resultMyString;
}
main方法
public static void main(String args[]) {
MyString tempFirstString = new MyString("Lionel Messi is the best football player in the world.");
MyString tempSecondString = new MyString("Messi");
int tempPosition = tempFirstString.locate(tempSecondString);
System.out.println("The position of \"" + tempSecondString + "\" in \"" + tempFirstString
+ "\" is: " + tempPosition);
MyString tempThirdString = new MyString("play");
tempPosition = tempFirstString.locate(tempThirdString);
System.out.println("The position of \"" + tempThirdString + "\" in \"" + tempFirstString
+ "\" is: " + tempPosition);
tempThirdString = tempFirstString.substring(1, 2);
System.out.println("The substring is: \"" + tempThirdString + "\"");
tempThirdString = tempFirstString.substring(5, 5);
System.out.println("The substring is: \"" + tempThirdString + "\"");
tempThirdString = tempFirstString.substring(5, 6);
System.out.println("The substring is: \"" + tempThirdString + "\"");
}
结果为
实现上述操作。