如何从cout中更改字符串的值

时间:2014-05-07 12:18:16

标签: string

void extractWord (string& str)

我必须编写一个在'*'之间提取单词的函数。 例如,使用以下三个测试用例:

string s = "This is to be *reversed*"

string s1 ="*Reversed* starts here";

string s2 = "This is *in* the middle";

并在每次函数调用后, s=reversed, s1=Reversed, s2=in

所以我想出来了......

void extractWord (string& str)

{
char target= '*';

int idx1=0;

while (str[idx1] != target)
idx1=idx1+1;

int idx2=idx1+1;
while (str[idx2] != target)
idx2=idx2+1;

for(int i=0;i<sizeof(str);i++)
     {
     if ((i>idx1)&&(i<idx2))
     cout<<str[i];
     }
}


int main()
{
string s="This is to be *reversed*";
string s1 = "*Reversed* starts here";
string s2= "This is *in* the middle";

extractWord(s);
cout<<endl;
extractWord(s1);
cout<<endl;
extractWord(s2);
cout<<endl;
}

但是如何将s的值更改为此函数的输出?

1 个答案:

答案 0 :(得分:0)

我稍微修改了你的代码。我希望这能解决你的问题:

//#include "stdafx.h"
#include < string >
#include < iostream >
using namespace std;

void extractWord (string& str)

{
char target= '*';

int idx1=0;

while (str[idx1] != target)
idx1=idx1+1;

int idx2=idx1+1;
while (str[idx2] != target)
idx2=idx2+1;

str=str.substr(idx1+1,idx2-idx1-1); //changed 
}


int main()
{
string s="This is to be *reversed*";
string s1 = "*Reversed* starts here";
string s2= "This is *in* the middle";

extractWord(s);
cout<<s<<endl; //changed 
extractWord(s1);
cout<<s1<<endl; //changed 
extractWord(s2);
cout<<s2<<endl; //changed 

    system("PAUSE");
    return 0;
}

现在,每次调用void extractWord(string&amp; str)时,它都只用*&#39; s之间的单词替换字符串。 我使用过std :: string :: substr函数。 &GT; http://www.cplusplus.com/reference/string/string/substr/

其他选项是制作在*&#39;之间返回单词的函数。

//#include "stdafx.h"
#include < string >
#include < iostream >
using namespace std;

string extractWord (string& str)

{
char target= '*';

int idx1=0;

while (str[idx1] != target)
idx1=idx1+1;

int idx2=idx1+1;
while (str[idx2] != target)
idx2=idx2+1;

return str.substr(idx1+1,idx2-idx1-1);
}


int main()
{
string s="This is to be *reversed*";
string s1 = "*Reversed* starts here";
string s2= "This is *in* the middle";
string res;
res=extractWord(s);
cout<<res<<endl;
res=extractWord(s1);
cout<<res<<endl;
res=extractWord(s2);
cout<<res<<endl;

    system("PAUSE");
    return 0;
}

但是,请注意,如果您的字符串不包含两个*或它有多个必须提取的单词,它就不起作用。我希望这能帮助你。