简体   繁体   English

C++:从两个符号之间提取字符串

[英]C++ : extracting string from between two symbols

I have the string String str = "my age is how old i am?how old are you?";我有字符串 String str = "my age is how old i am? how old are you?";

And I want to extract just the string "how old are you" and place it in another variable.我只想提取字符串“你多大了”并将其放在另一个变量中。

How can I do this?我怎样才能做到这一点?

You can use the substring method: http://www.cplusplus.com/reference/string/string/substr/您可以使用子字符串方法: http : //www.cplusplus.com/reference/string/string/substr/

int first = str.find('?')
String ageStr = str.substr(first, str.find('?', first) - first);

This way you select the part of the string between the position of the first question mark, and the position of the second question mark...这样您就可以选择第一个问号位置和第二个问号位置之间的字符串部分...

#include <string>
#include <iostream>
using namespace std;
string  GetStringInBetween(string Src,string FirstTag, string Secondag)
{
    size_t FirstPos,SecondPos;
    string newstr="";
    FirstPos = Src.find(FirstTag);
    if (FirstPos != string::npos)
    {
        FirstPos++;
        SecondPos = Src.find(Secondag, FirstPos );
        if (SecondPos != string::npos)
        {
            newstr = Src.substr(FirstPos , SecondPos - FirstPos);
        }
    }
    return newstr;
}
int main()
{

    string str = "?how old are you?";
    string nstr = GetStringInBetween(str, "?", "?");
    cout << nstr;
    return 0;
}
for(int i=0;i<strlen(str);i++)
{
    if(str[i] != '?')
    {
        cout<<str[i];
    }
}

You can add any symbol of your choice in place of ?您可以添加任何您选择的符号来代替? . .

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

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