编写一个程序对字符串结构进行增删改查操作java顺序串
时间: 2024-05-11 08:14:49 浏览: 73
java字符串数组的增删改查
以下是一个简单的Java顺序串类,包含了基本的增删改查操作:
```java
public class SeqString {
private char[] data;
private int length;
public SeqString() {
data = new char[0];
length = 0;
}
public SeqString(String str) {
data = str.toCharArray();
length = str.length();
}
public SeqString(char[] arr) {
data = arr.clone();
length = arr.length;
}
public int length() {
return length;
}
public char charAt(int index) {
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException("Index out of range: " + index);
}
return data[index];
}
public SeqString substring(int beginIndex, int endIndex) {
if (beginIndex < 0 || endIndex > length || beginIndex > endIndex) {
throw new IndexOutOfBoundsException("Index out of range: " + beginIndex + ", " + endIndex);
}
char[] newData = new char[endIndex - beginIndex];
System.arraycopy(data, beginIndex, newData, 0, endIndex - beginIndex);
return new SeqString(newData);
}
public SeqString insert(int offset, String str) {
if (offset < 0 || offset > length) {
throw new IndexOutOfBoundsException("Index out of range: " + offset);
}
char[] newData = new char[length + str.length()];
System.arraycopy(data, 0, newData, 0, offset);
System.arraycopy(str.toCharArray(), 0, newData, offset, str.length());
System.arraycopy(data, offset, newData, offset + str.length(), length - offset);
return new SeqString(newData);
}
public SeqString delete(int offset, int len) {
if (offset < 0 || offset + len > length) {
throw new IndexOutOfBoundsException("Index out of range: " + offset + ", " + len);
}
char[] newData = new char[length - len];
System.arraycopy(data, 0, newData, 0, offset);
System.arraycopy(data, offset + len, newData, offset, length - offset - len);
return new SeqString(newData);
}
public SeqString replace(String oldStr, String newStr) {
int index = indexOf(oldStr);
if (index == -1) {
return this;
}
SeqString prefix = substring(0, index);
SeqString suffix = substring(index + oldStr.length(), length);
return prefix.concat(newStr).concat(suffix.replace(oldStr, newStr));
}
public int indexOf(String str) {
int maxIndex = length - str.length();
for (int i = 0; i <= maxIndex; i++) {
boolean match = true;
for (int j = 0; j < str.length(); j++) {
if (data[i + j] != str.charAt(j)) {
match = false;
break;
}
}
if (match) {
return i;
}
}
return -1;
}
public SeqString concat(String str) {
return insert(length, str);
}
@Override
public String toString() {
return new String(data);
}
}
```
使用示例:
```java
SeqString str = new SeqString("hello");
System.out.println(str); // hello
System.out.println(str.charAt(1)); // e
System.out.println(str.substring(1, 4)); // ell
System.out.println(str.insert(3, "world")); // helworldlo
System.out.println(str.delete(2, 3)); // hewlo
System.out.println(str.replace("ew", "l")); // hllo
System.out.println(str.indexOf("l")); // 2
System.out.println(str.concat("world")); // helloworld
```
阅读全文