计算字符串中的多个字符

Counting Multi-Character Characters in String

本文关键字:字符 字符串 计算      更新时间:2023-10-16

例如,如何计算"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;
}