繁体   English   中英

函数在c ++中的字符串中查找只能与第一个字符一起使用吗?

[英]does function find in strings in c++ work only with the first char?

我想在由数字和char组成的string找到一个char ,如果发现程序执行了一些操作,但是当我使用find()函数时,仅当我要查找的char仅在开始时才返回true。字符串!

例:这是问题的一部分!
用户输入3个字符串s1,s2,s3; 在前两个字符串之间有一个char'a 'a' = '+' ,在s2和s3之间有一个char'b 'b' = '=' (这三个字符串应该是数字),但是如果s2是一个包含字母'm'的单词'm' ,程序将s1和s3转换为整数并写入完整运算ex:如果i / p为3247 + 5machula2 = 3749,则o / p将为3247 + 502 = 3749

这是我正在尝试解决的问题, http://www.spoj.com/problems/ABSYS/和我的代码的这一部分有问题:

int T;
int x,y,z;
string s1 ;
string s2  , s3 ;
char a , b;
cin>>T;
for(int i=0 ; i<T ; i++)
{
         cin>>s1>>a>>s2>>b>>s3;


for (int k=0; k<s2.size(); k++)
{ 
    if (k==s2.find("m"))
    {     
        stringstream ss(s1);
        stringstream ss3(s3);

        ss>>x;
        ss3>>z;

        cout<<s1<<" "<<a<<" "<<z-x<<" "<<b<<" "<<s3<<endl;
    }   
    else break;       
}

这是一个循环,在第二个字符串上循环,如果找到一个字符'm'它应该执行上面提到的操作,但是这里的问题是,仅当'm'在字符串的开头并且没有其他位置时,它才有效。

else break; 防止循环不断循环。

它仅在开始时才起作用的原因是,如果不是这样,则会中断循环,因此它没有机会检查其余部分:

[first iteration]
if (0 == s2.find("m")) //if found at beginning
    //do stuff
else break; //exit loop if not found at beginning

如果您只是想查看是否存在m,请使用find()而不是循环:

if (s2.find('m') != std::string::npos)
    //"m" found in string, do the operations on s1 and s3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM