代码:
package com.one;
public class MyString {
public static final int MAX_LENGTH = 10;//the maximal length.
int length;
char[] data;
public MyString() {
length = 0;
data = new char[MAX_LENGTH];
}// of the first constructor
public MyString(String paraString) {
data = new char[MAX_LENGTH];
length = paraString.length();
for (int i = 0; i < length; i++) {
data[i] = paraString.charAt(i);
}// of for i
}// of the second constructor.
public String toString() {
String resultString = "";
for (int i = 0; i <length; i++) {
resultString += data[i];
}// of for i
return resultString;
}// of toString
/**
* Locate the position of a substring
* @param paraMyString
* @return The first position. -1 for no matching
*/
public int locate(MyString paraMyString) {
boolean tempMatch = false;
for (int i = 0; i < length - paraMyString.length + 1; i++) {
//Initialize
tempMatch = true;
for (int j = 0; j < paraMyString.length; j++) {
if (data[i + j] != paraMyString.data[j]) {
tempMatch = false;
break;
}// of if
}// of for j
if (tempMatch) {
return i;
}// of if
}// of for i
return -1;
}// of locate
public MyString substring(int paraStartPosition, int paraLength) {
if (paraStartPosition + paraLength > length) {
System.out.println("The bound is exceeded");
return null;
}// of if
MyString resultMyString = new MyString();
resultMyString.length = paraLength;
for (int i = 0; i < paraLength; i++) {
resultMyString.data[i] = data[paraStartPosition + i];
}// of for i
return resultMyString;
}// of substring
public static void main(String[] args) {
MyString tempFirstString = new MyString("I like ik.");
MyString tempSecondString = new MyString("ik");
int tempPosition = tempFirstString.locate(tempSecondString);
System.out.println("The position of \"" + tempSecondString + "\" in \"" + tempFirstString
+ "\" is: " + tempPosition);
MyString tempThirdString = new MyString("ki");
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 + "\"");
}// of main
}// of class MyString
运行结果:
The position of "ik" in "I like ik." is: 3
The position of "ki" in "I like ik." is: -1
The substring is: " l"
The substring is: "e ik."
The bound is exceeded.
The substring is: "null"