计算字符串中的多字符字符 [英] Counting Multi-Character Characters in String

查看:136
本文介绍了计算字符串中的多字符字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如何计算 OAEKOTJEOTJ

if (s[i] == 'TJ') and (s[i] == 'T'+'J')
    x += 1;

第一个给我一个错误,第二个不计数。我需要一个初学者的解决方案,我还没有学到很多关于c ++命令。感谢

First one gives me an error, second one doesn't count. I need a beginner solution to this, I haven't learned very much about c++ commands yet. Thanks

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

That's the excerpt from my code, it doesn't count any tj, tJ, Tj or 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;

编辑:
根据您的代码:

Based on your code:

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;

这篇关于计算字符串中的多字符字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆