字符串学习小结
字符串:串使用串存储结构来储存字符串,串存储结构也是一种线性存储结构,因为字符串中的字符之间也具有"一对一"的逻辑关系,但是串存储结构只用来存储字符串。
串存储结构

串的定长顺序储存
就是我们在C语言中使用的数组,在使用数组前,我们都要申请足够大的空间来存储字符串,且大小不能改变,这也是不方便的地方。
#include <iostream> using namespace std; int main() { char str[12] = "helloworld"; cout << str << endl; return 0; }
数组根据创建方式的不同,又分为静态数组和动态数组,我们在定长顺序存储中使用的就是静态数组,而在堆分配储存中,我们将会用到动态分配数组。
堆分配储存
相比串的定长储存,堆分配存储的优势在于分配空间可变,通过下面的“字符串结合”可以体现这种特性:
#include <iostream> #include <cstring> #include <cstdlib> #pragma warning(disable: 4996) using namespace std; int main() { char *s1 = new char[7]; char *s2 = new char[7]; strcpy(s1, "hello,"); strcpy(s2, "world"); cout << "s1:" << s1 << endl; cout << "s2:" << s2 << endl; int length1 = strlen(s1); int length2 = strlen(s2); char *s3 = s1; s1 = new char[length1 + length2 + 2]; strcpy(s1, s3); strcat(s1, s2); cout << "结合之后:" << s1 << endl; delete []s1; delete []s2; system("PAUSE"); return 0; }
串的块链存储结构
这种方式存储串是通过链表来存储,链表的优势在于
- 长度可变
- 节点数据可多可少
- 节点数据的操作方便
对于每个节点的字符串,我们可以使用自定长度的字符数组储存,当最后字符储存不足时可以用'#'等特殊字符占位,将字符区分开。
#include <iostream> #include <string> using namespace std; #define SIZE 5 struct Link { char arr[SIZE]; Link* next; }; Link* InitLink(Link* head, string str) { int n = str.size() / SIZE; if (str.size() % SIZE) { n++; } head = new Link; head->next = NULL; Link *temp = head; for (int i = 0; i < n; ++i) { int j = 0; for (; j < SIZE; ++j) { if (i * SIZE + j < str.size()) { temp->arr[j] = str[i * SIZE + j]; } else { temp->arr[j] = '#'; } } if (i * SIZE + j < str.size()) { Link* list = new Link; list->next = NULL; temp->next = list; temp = temp->next; } } return head; } void Display(Link* head) { Link *temp = head; int n = 0; while (temp) { cout << "第" << ++n << "块:" << endl; for (int i = 0; i < SIZE; ++i) { cout << temp->arr[i]; } cout << endl << endl; temp = temp->next; } } int main() { Link *head = NULL; string s = "hello, world!!!"; head = InitLink(head, s); Display(head); system("PAUSE"); return 0; }
BF算法
BF算法就是将两个字符串逐一匹配。
下面截图能够很好展示,BF算法原理

代码实现:
#include <iostream> #include <string> using namespace std; bool Size(const string&, const string&, int); int BF(const string &mainstr, const string &substr) { int k = 0; if (!Size(mainstr, substr, k)) { return -1; } size_t i = 0, j = 0, n = 0; while (i < mainstr.size()) { if (mainstr[i] == substr[j]) { ++n; ++j; if (n == substr.size()) { return (i - n + 1); } } else { if (!Size(mainstr, substr, ++k)) { return -1; } j = 0; n = 0; } ++i; } return -1; } bool Size(const string &s1, const string &s2, int i) { return s1.size() >= s2.size() + i; } int main() { string s1 = "hello, biubiubiu, you are pig, lololo!"; string s2 = "pig"; int n = BF(s1, s2); if (n == -1) { cout << s1 << "中未找到" << s2 << endl; } else { cout << n << endl; } system("PAUSE"); return 0; }

浙公网安备 33010602011771号