0

例如,您如何计算"TJ"in的出现次数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

4

3 回答 3

2

尝试使用:

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;
于 2012-11-29T01:48:08.340 回答
1

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按搜索模式的长度前进。(也见克里斯的评论。)

于 2012-11-29T01:58:03.613 回答
0

尝试这个:

#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;
}
于 2012-11-29T02:15:31.220 回答