int i = 0; while (str[i] == ch)i++; int j = str.size() - 1; while (str[j] == ch)j--; str = str.substr(i, j + 1 - i);作用
时间: 2023-12-06 07:03:04 浏览: 95
这段代码的作用是去除字符串 str 开头和结尾处的连续字符 ch。
代码首先定义了变量 i 和 j,并分别从字符串的开头和结尾开始遍历,跳过所有与 ch 相同的字符。然后使用 substr() 函数提取出中间没有被跳过的部分,并将其赋值给原来的字符串 str。最终返回的 str 就是去除了开头和结尾处连续字符 ch 的字符串。
相关问题
int i = 0; while (str[i] == ch)i++; int j = str.size() - 1; while (str[j] == ch)j--; str = str.substr(i, j + 1 - i);
这段代码的作用是去除字符串str开头和结尾的字符ch,并返回剩余部分的子字符串。具体来说,它首先定义了一个变量i和j,分别表示字符串开头和结尾的字符ch的个数,然后通过while循环找到第一个不是ch的字符的下标i,和最后一个不是ch的字符的下标j。最后,调用substr方法返回从i到j的子字符串,即是去除开头和结尾的ch后的字符串。
#include <stdio.h> #include <string.h> #define MAXLEN 100 // 定义最大串长 typedef struct { char ch[MAXLEN]; // 存储串的字符数组 int length; // 串的长度 } SqString; // 初始化串 void InitString(SqString *s, char *str) { int len = strlen(str); for (int i = 0; i < len; i++) { s->ch[i] = str[i]; } s->length = len; } // 输出串 void PrintString(SqString s) { for (int i = 0; i < s.length; i++) { printf("%c", s.ch[i]); } printf("\n"); } // BF模式匹配算法 int Index(SqString s, SqString t) { int i = 0, j = 0; while (i < s.length && j < t.length) { if (s.ch[i] == t.ch[j]) { i++; j++; } else { i = i - j + 1; j = 0; } } if (j == t.length) { return i - j + 1; // 返回匹配成功的位序 } else { return -1; // 返回匹配失败 } } int main() { SqString s, t; char str1[MAXLEN] = "aaaabcdcccc"; char str2[MAXLEN] = "abcd"; InitString(&s, str1); InitString(&t, str2); printf("主串为:"); PrintString(s); printf("模式串为:"); PrintString(t); int pos = Index(s, t); if (pos == -1) { printf("未找到匹配的子串!\n"); } else { printf("匹配成功,位序为:%d\n", pos); } return 0; }解释这段代码
这段代码实现了 BF 模式匹配算法。具体解释如下:
1. 定义了一个结构体 SqString,用于存储字符串及其长度。
2. 定义了初始化字符串函数 InitString,用于将字符串转换为 SqString 类型,并保存其长度。
3. 定义了输出字符串函数 PrintString,用于输出 SqString 类型的字符串。
4. 定义了 BF 模式匹配算法函数 Index,用于在主串 s 中查找模式串 t,返回匹配成功的位序,如果匹配失败则返回 -1。
5. 在主函数中,先定义了两个 char 类型的数组 str1 和 str2,分别表示主串和模式串,并将其转换为 SqString 类型。
6. 调用 Index 函数,在主串 s 中查找模式串 t,并输出匹配结果。
总的来说,这段代码实现了 BF 模式匹配算法的基本流程,包括字符串的初始化和输出,以及匹配算法的具体实现。
阅读全文
相关推荐

















