Day 19
1. Background
今天是学习java的第十九天,今天学习的是字符数组的匹配和按位置输出。
2. Code
package datastructure;
public class MyString {
// The maximal length.
public static final int MAX_LENGTH = 10;
int length;
// The data.
char[] data;
/**
*************
* Construct an empty char array.
*************
*/
public MyString() {
length = 0;
data = new char[MAX_LENGTH];
} // Of the first construct
/**
*************
* Reload Mystring.
*
* @param paraString The given string.
*/
public MyString(String paraString) {
data = new char[MAX_LENGTH];
length = paraString.length();
// Copy data
for (int i = 0; i < length; i++) {
data[i] = paraString.charAt(i);
} // Of for i
} // Of the secend data
/**
*************
* 判定字符数组中是否包含给定数组
*
* @param paraMyString The given string.
* @return -1 or The given string's position on data.
* ************
*/
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
/**
*
* 按指定的位置和长度输出字符数组
*
* @param paraPosition The given position.
* @param paraLength The given length.
* @return null or match.
*/
public MyString subString(int paraPosition, int paraLength) {
if (paraPosition + paraLength > length) {
System.out.println("exceed.");
return null;
}
MyString resultMyString = new MyString();
resultMyString.length = paraLength;
for (int i = 0; i < paraLength; i++) {
resultMyString.data[i] = data[paraPosition + i];
} // Of for i
return resultMyString;
} // Of subString
public String toString() {
String resultString = "";
for (int i = 0; i < length; i++) {
resultString += data[i];
} // Of for i
return resultString;
}// Of toString
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 + "\"");
}
}
运行结果:
3. Summarize
今天的学习总的来说理解上没有太大的压力,主要是代码实现上。字符数组的输出和判定对位置的要求格外的严格,所以在写代码的时候每一个数字出错都会造成整个程序结果的错误。而这种错误是编译器无法帮助我们察觉的,所以在写代码的时候需要格外的注意,每一个循环和方法,写数字前都要想好为什么这里要这么写,以及写了之后程序会怎么运行,会运行到哪一步再停下。