您的位置:首页 > 理论基础 > 数据结构算法

数据结构——串的定义与基本操作

2017-09-17 15:08 288 查看
/**

* 1.串的定义

* 串是由零个或多个字符组成的有限序列。

* 串中字符的个数称为串的长度,含有零个元素的串叫空串。

* s =null;

* s = “”;//empty

* s = “ ”;//空格串

* s = “Hello World 5201314!”;//常规串

* 串中任意连续字符组成的子序列称为该串的子串,包含子串的串称为主串。

* 2.串的存储结构

* 1)定长顺序存储表示

* public class Str{

* int MAX_STR_LEN = 255; //字符串最大长度

* char[] chs = new char[MAX_STR_LEN+1];//字符数组

* }

* 两种表示方法:0号单元存放数组长度,或者最后一个单元存放”\0”表示串的终结

* 2)堆分配存储表示

* public class Str{

* int length;//长度根据实际取值

* char[] chs = new char[length+1];

* }

* Java取消了指针,故从代码上看,两种分配表示并不如C语言表示那样区别明显,

* 但是,实际上我个人觉得差别没那么大,定长是事先写死存储的容量,如果字符少,则

* 多余部分元素为null值,如果字符多,超过了容量,则会从前到后截取满足容量的字符,

* 之后的舍弃。变长表示则是根据传入字符数组的实际长度创建一样长度的字符数组。

*/

package string;

import java.util.Arrays;

/**
* @author 芜情
*   串的原子操作,由于变长实现的更加实用,以堆分配表示为例
*   Java中定义好了String类型,这里模拟的是底层实现
*/
public class MyString {
private int capacity;//字符串长度
private char[] string;//字符数组
//赋值
public void strAssign(char[] chs){
if(this.string != null){
this.string = null;//释放原串空间
this.capacity = 0;
}
if(chs == null){
this.capacity = 0;
this.string = null;
return;
}
int len = chs.length;
this.string = new char[len + 1];
for(int i = 0; i < len; i++){
string[i] = chs[i];
}
string[len] = '\0';
this.capacity = len;
}
//取串长度
public int strLength(){
return this.capacity;
}
//串比较
public boolean strCompare(MyString t){
for(int i = 0; i < this.capacity && i < t.capacity; i++){
if(this.string[i] != t.string[i]){
return false;
}
}
return this.capacity - t.capacity == 0;
}
//串连接
public void concat(MyString t){
int temp= this.capacity;
int len = this.capacity + t.capacity;
string = Arrays.copyOf(string, len + 1);
for(int i =temp,  j = 0; i < len + 1; ++i, ++j){
string[i] = t.string[j];
}
string[len] = '\0';
this.capacity = len;
}
//求子串
public MyString subString(int beginIndex, int len){
if(beginIndex < 0 || beginIndex >= this.capacity || len <= 0 || len > this.capacity - beginIndex){
throw new RuntimeException("索引错误");
}
MyString t = new MyString();
t.capacity = len;
t.string = new char[len +1];
System.arraycopy(string, beginIndex, t.string, 0,len);
string[len] = '\0';
return t;
}
//串清空
public void clear(){
this.string = null;
this.capacity = 0;
}
//重写toString方法,方便测试
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < this.capacity; i++){
sb.append(string[i]);
}
return sb.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: