串的存储结构
定长串,用来做串操作的测试
public class myString {
public static final int MAXLEN = 7; // 串的最大长度
private static char[] s; // 定长串s
private static int len_s;
myString() {
s = new char[MAXLEN]; // 初始化定长主串
s[0] = 'a';s[1] = 'b';s[2] = 'c';
s[3] = 'd';s[4] = 'e';s[5] = 'f';
len_s = 6; // 初始化主串长度
}
}
串的基本操作
定长串的插入
插入位置pos将主串分为两部分,分别是LA、LB;待插入子串的长度LC
插入串有三种情况:
1、LA + LB + LC <= MAXLEN,直接将B后移,再将C插入
2、LA + LB + LC > MAXLEN && pos + LC <= MAXSIZE,部分B会被抛弃,C全部插入
3、LA + LB + LC > MAXLEN && pos + LC > MAXSIZE,全部B会被抛弃,C部分插入
// 定长串的插入
public void StrInsert(int pos, char[] t) {
System.out.println(Arrays.toString(s));
System.out.println(Arrays.toString(t));
int len_s = this.len_s; // 主串长度
int len_t = t.length; // 字串长度
if (len_s + len_t <= MAXLEN) { // LA + LC +LB <= MAXLEN
for (int i = len_s + len_t - 1; i >= pos + len_t; i--) { // LB向后移动len_t个位置,给LC腾出空间
s[i] = s[i - len_t];
}
for (int i = 0; i < len_t; i++) { // 将t插入到pos位置
s[i + pos] = t[i];
}
} else if (len_s + len_t > MAXLEN) { // LA + LC +LB > MAXLEN
if (pos + len_t <= MAXLEN) { // LA + LC <= MAXLEN
for (int i = MAXLEN - 1; i >= pos + len_t; i--) { // 部分LB向后移动len_t个位置
s[i] = s[i - len_t];
}
for (int i = 0; i < len_t; i++) { // 将t插入到pos位置
s[i + pos] = t[i];
}
} else if (pos + len_t > MAXLEN) { // LA + LC > MAXLEN,LB全部去除,部分LC插入剩下部分
for (int i = 0; i < MAXLEN - pos; i++) {
s[i + pos] = t[i];
}
}
}
System.out.println(Arrays.toString(s));
}
定长串的删除
// 定长串的删除
public void StrDelete(int pos, int len) { // [pos, pos + len)
if (pos < 0 && pos + len > len_s) // 删除的长度或位置不合法
return;
for (int i = pos; i < len_s - len; i++) { // 删除位置后面的字符向前移,代替原字符
s[pos] = s[pos + len];
}
System.out.println(Arrays.toString(s));
}
字符串的比较
// 字符串的比较
public int StrCompare(char[] t) {
int len_t = t.length;
for (int i = 0; i < len_s && i < len_t; i++) {
if (s[i] != t[i]) {
return (int) s[i] - (int) t[i];
}
}
return len_s - len_t;
}
连接字符串
连接字符串的算法与子串插入算法相似,等同于在pos = len_s的位置
// 连接字符串
public void StrCat(char[] t) {
StrInsert(len_s, t);
}