检查相同的字母是否在字符串中连续出现 3 次
Checking if same letter appears 3 times consecutively in string
// a is some string;
b=a.length;
for(int i=1; i<b; i++)
{
if(a[i-1]==a[i]==a[i+1])
{
cout <<a[i]<<endl;
//more to add
}
}
想要检查是否出现相同的 3 个或更多字母 - 这里有什么问题?
您的具体问题是:
a[i-1]==a[i]==a[i+1]
评估为
(a[i-1] == a[i]) == a[i+1]
要么是
true == a[i+1]
false == a[i+1]
这两种可能都不是你想要的。此外,当i == a.size()
时,a[i+1]
会读出字符串的末尾,这是未定义的行为。
此外,您的标题声称您要检查一个字母是否出现超过 2 次,但您的代码即使固定,也会检查它是否连续出现 3 次。如果您确实要检查 3 次出现,只需使用 std::count
:
for (int i = 0; i < a.size(); ++i) {
if (std::count(a.begin(), a.end(), a[i]) >= 3) {
// success!
}
}
检查字符串中 N 个连续字符的另一种实现(线性时间复杂度(,
const std::size_t N = 3;
std::string text { "this is a string" };
std::size_t index = 0;
std::size_t num_same_char = 1;
while (index + N - num_same_char < text.size()) {
if (num_same_char == N) {
// found at index
break;
}
if (text[index] == text[index + num_same_char]) {
num_same_char++;
}
else {
num_same_char = 1;
index += num_same_char;
}
}
// a is some string;
b=a.length;
for(int i=1; i<b-1; i++) **//Iterate till b-1 not b**
{
if(a[i-1]==a[i] && a[i]==a[i+1])
{
cout <<a[i]<<endl;
//more to add
}
}
希望这有帮助。
相关文章:
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 检查连续对的字符串C++
- 不带连续 1 的位字符串,使用自上而下的 DP
- 使用 fprintf 连续写入字符串
- 将字符串分为连续的非空格字符的序列
- "map"容器C++是否对字符串的连续子字符串应用 Rabin-Karp 算法?
- 连续字符串输入的C 动态数组
- 从带有位偏移量的std::字符串中按字节提取连续位
- 从一个字符串中获取 2-5 个连续的单词短语,我得到了 2 个工作,但在做 3 个时遇到麻烦
- 删除字符串数组中的所有连续重复项
- 将字符串重新排序为没有连续相同字符的字符串
- 静态 c++ 对象中的 JNI 环境指针并调用连续两次使用字符串参数的 Java 函数会使 JVM 崩溃
- C++,转换字符串,使连续下划线序列变为单个下划线
- 删除字符串中的连续重复值
- 使用 std::cin 的连续字符串输入
- 从字符串中检索数据并连续写入数据库
- 如何编写一个函数来计算字符串中相同的连续字母
- 尽量减少映射<字符串、字符串的连续相等提取次数>
- 在连续内存中存储相同长度的字符串
- 重用字符串流来连续解析多个字符串的值