简体   繁体   English

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

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

I want to find a char in a string consists of numbers and chars , if it's found the program does some operations , but when I use function find() , it returns only true if the char I am looking for is ONLY at the beginning of the string !!!!! 我想在由数字和char组成的string找到一个char ,如果发现程序执行了一些操作,但是当我使用find()函数时,仅当我要查找的char仅在开始时才返回true。字符串!

Ex : This is part of the problem ! 例:这是问题的一部分!
The user enters 3 strings s1 , s2 , s3 ; 用户输入3个字符串s1,s2,s3; between the first 2 strings there's char 'a' = '+' and between s2 and s3 there's char 'b' = '=' (The 3 strings are supposed to be numbers ) but if s2 is a word that includes the letter 'm' , the program converts s1 and s3 into integeres and writes the full operation ex : if i/p is 3247 + 5machula2 = 3749 then o/p would be 3247 + 502 = 3749 在前两个字符串之间有一个char'a 'a' = '+' ,在s2和s3之间有一个char'b 'b' = '=' (这三个字符串应该是数字),但是如果s2是一个包含字母'm'的单词'm' ,程序将s1和s3转换为整数并写入完整运算ex:如果i / p为3247 + 5machula2 = 3749,则o / p将为3247 + 502 = 3749

Here's the problem I'm trying to solve http://www.spoj.com/problems/ABSYS/ and this part of my code which has the problem : 这是我正在尝试解决的问题, 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;       
}

This is a loop that loops on the second string and if it find a char 'm' it should do what's mentioned above , but the problem here is that it only works if 'm' is at the beginning of the string and no place else. 这是一个循环,在第二个字符串上循环,如果找到一个字符'm'它应该执行上面提到的操作,但是这里的问题是,仅当'm'在字符串的开头并且没有其他位置时,它才有效。

Your else break; else break; prevents the loop from ever looping. 防止循环不断循环。

The reason it only works when it's at the beginning is because you break out of the loop if it isn't, so it has no chance to check the rest: 它仅在开始时才起作用的原因是,如果不是这样,则会中断循环,因此它没有机会检查其余部分:

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

Instead of the loop, if you're just trying to see whether there is an m, just use find() : 如果您只是想查看是否存在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