String類的字串操作(C 實現)

2021-06-26 04:47:23 字數 2094 閱讀 3278

之前那篇,函式也有些小問題,比如只判斷了是否為空,如果傳入的就是空字串的情況呢?並且length成員變數也沒怎麼試用

並且這次的**加入了c++語法中拷貝構造和拷貝賦值函式的**實現

#include

#include

#include

using namespace std;

#pragma warning(disable:4996)

#pragma warning(once:4996)

class string

;string::string(void)

string::~string(void)

}string::string(char* str)

count = len + 1;

count = count * 2;     //這裡用現有容量的二倍作為申請空間大小,避免了每次都要申請空間

data = new char[count];

if (null == data)

strncpy(data, str, len);

length = len;

data[length] = '\0';   //字串陣列的下標從0開始,所以len也就是length代表的就是字串緊跟著的位置

}//拷貝建構函式的實現

string::string(const string& str)

count = str.length + 1;

count = count * 2;

data = new char[count];     //避免淺拷貝問題

if (null == data)

strncpy(data, str.data, str.length);

length = str.length;

data[length] = '\0';

}//拷貝賦值的實現

const string& string::operator= (const string& str)

//避免自拷貝

if (this == &str)

//如果內容為空的情況

if ((null == str.data) || (0 == str.length))

int size = count;    //size儲存舊容量

count = str.length + 1;

count = count * 2;

char* tmp = new char[count];   //申請新記憶體

if (null == tmp)

strncpy(tmp, str.data, str.length);

length = str.length;

tmp[length] = '\0';

if (null != data)

data = tmp;    //指向新記憶體

return *this;

}void string::output()

printf("%s\n", data);

}bool string::pushback(char* str)

int left = count - length - 1;   //count剩餘大小,1代表'\0'

int size = count;

//剩餘記憶體足夠情況下,直接在這個記憶體中存入新字串

if (left >= len)

//此時是剩餘記憶體不夠的情況,就需要重新計算拼接後所需的大小,並重新申請空間

count += len;

count = count * 2;

char* tmp = new char[count];

if (null == tmp)

strncpy(tmp, data, strlen(data));

strncpy(tmp + strlen(data), str, len);

length = strlen(tmp);

tmp[length] = '\0';

if (null != data)

data = tmp;          //指向新記憶體

return true;

}int main()

C 字串string操作

相比於c語言而言,c 提供了太多的寫好了的型別和方法,其中string型別就是用起來特別方便的一種。那麼問題來了,既然有c語言的char型,為什麼還要學習string型別呢?我碰到過的也是最主要的乙個原因就是string型別更節省空間,用多少開多少,而char型別的陣列就不是了,必須開最大值。其次還...

c 字串string的操作

1.字串的宣告 include include include using namespace std int main else cout 方法2,string npos可強制轉換為 1 n int local local static cast s.find make 20 if local 1...

c 字串string的操作

1 include 2 include 3 include 45 using namespace std 67 intmain 879 else 82 83 cout 方法2,string npos可強制轉換為 1 n 84int local 85 local static cast s.find ...