计算字符串中的多个字符
Counting Multi-Character Characters in String
例如,如何计算"TJ"
在OAEKOTJEOTJ
中的出现次数?
if (s[i] == 'TJ') and (s[i] == 'T'+'J')
x += 1;
第一个给了我一个错误,第二个不算数。我需要一个初学者的解决方案,我还没有学到太多关于c++命令的知识。感谢
int x = 0
string s;
cin >> s;
for (int i = 0; i < 100; i++)
if (s[i] == T || s[i] == t) && (s[i+1] == J || s[i+1] == j)
x += 1
cout << x << endl;
这是我代码的摘录,它不包括任何tj、tj、tj或tj
尝试使用:
if(s[i] == 'T' && s[i+1] == 'J') // and make sure you do not run out of bounds of string with index i.
x += 1;
编辑:基于您的代码:
int x = 0
string s;
cin >> s;
for (int i = 0; i < 100; i++)
if (s[i] == T || s[i] == t) && (s[i+1] == J || s[i+1] == j)
x += 1
cout << x << endl;
你应该这样做:
int x = 0
string s;
cin >> s;
for (int i = 0; i < s.length()-1; i++) // use size of string s.length()-1 to iterate the string instead of 100
if (s[i] == 'T' || s[i] == 't') && (s[i+1] == 'J' || s[i+1] == 'j') // compare the ascii values of characters like - 'T' 'J' etc.
x += 1
cout << x << endl;
std::string
提供了一个函数find
,它在字符串中搜索子字符串,包括多字符子字符串(下面,我使用的是C++11语法):
#include <iostream>
#include <string>
int main()
{
using namespace std;
string text { "OAEKOTJEOTJ" };
unsigned int occ { 0 };
size_t pos { 0 };
for (;;) {
pos = text.find("TJ",pos); // Search for the substring, start at pos
if (pos == string::npos) // Quit if nothing found
break;
++pos; // Continue from next position
++occ; // Count the occurrence
}
std::cout << "Found " << occ << " occurrences." << std::endl;
}
按照上面的方法,我们在每场比赛后只前进一个字符。根据是否/如何处理重叠匹配,我们可能希望将pos
提前搜索模式的长度。(参见chris的评论。)
试试这个:
#include <locale> // for tolower() function
string tolower(string s) {
tolower(s[0]);
tolower(s[1]);
return s;
}
...
int main() {
string s;
cin >> s;
int n = s.size(),cont = 0;
for(int i = 0; i < n ; ++i) {
if(tolower(s.substr(i,2)) == "tj") {
++cont;
}
}
cout << cont << endl;
return 0;
}
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数