比较两个字符串add(空格,逗号,点等)c ++

时间:2014-03-28 13:22:40

标签: c++ string loops text alter

嗨,我希望有人可以帮助我,我正在尝试修复我的字符串输出,我得到一个输出,但它全部捣碎成一个长字符串没有空格等,所以我试图使用旧的字符串,之前有逗号空间等,并在新的替换它们。我真的不知道怎么做这个我用c ++尝试过这个,如果我在我的程序中运行下面的代码它会崩溃我不知道如何解决它。

string input2 = "chq pste uwdn or mfwiejjne
u aaul mvabe mrv po zso, jnp kg co urfrsrvwn,
azh s bmmpd lanmf kuupv chqvw, xf opsh azh ojtfpwb mmhw;
wizi tnaz vgfs imdu i tenn ttijn, a tmnn fav lqe tsfny niw,
jnp paee mpgwe ur lqe niw uogh yuapi.
swd u wzjlx lsee esen pqeun ttijn, fav hnaoi uxmqw vaobtawg epgf,
ddshyizk xaoy xzn vqmdb or xzn mavfrns xg fhqvw chq gjrcwil bizkk;
chqvw vipraphf’w sul m kdrmyij, jnp rgxn m tmapxi yuoi,
efm ehifrns jmul aj lqe xmfwef’w ornsw.
a fixp saiei swd ss fxw, rsj jlieqb nukzc azh vjy
u lwjr xecn wmxwa lmthrns aach xso bogrvb bk xzn stsjn;
wtmdn i exswd ar lqe dssmwmc, ga oz xzn pmzwvezxk prqc,
a qemv ac iz xzn dqih qemvl’b cavw.";


string result = "THELAKEISLEOFINNISFREEIWILLARISEANDGONOWANDGOTOINNISFREEANDASMALLCAB
INBUILDTHEREOFCLAYANDWATTLESMADENINEBEANROWSWILLIHAVETHEREAHIVEFORTH
EHONEYBEEANDLIVEALONEINTHEBEELOUDGLADEANDISHALLHAVESOME
PEACETHEREFORPEACECOMESDROPPINGSLOWDROPPINGFROMTHEVEILSOFTHEMORNINGTOWHERETHE
CRICKETSINGSTHEREMIDNIGHTSALLAGLIMMERANDNOONAPURPLEGLOWANDEVENINGFULLOFTHELINNET
SWINGSIWILLARISEANDGONOWFORALWAYSNIGHTANDDAYIHEARLAKEWATERLAPPINGWITHLOWSOUNDSB
YTHESHOREWHILEISTANDONTHEROADWAYORONTHEPAVEMENTSGREYIHEARITINTHEDEEPHEARTSCORE";

string original = input2; //original unchanged text with spaces, commas etc
string tempResult = result; //the new output without spaces, commas, dots etc
string fixed = ""; //string to be altered with spaces, commas etc
int originalSize = input2.size();
int i = 0, j = 0;

for(i, j; i < originalSize ;i++)
{
  if(isalnum(original[i]) || !original[i] == ' ')
{
  fixed += tempResult[j];
  j++;
}
else
{
  fixed += tempResult[j];
}
}

1 个答案:

答案 0 :(得分:0)

正如评论中所述,提供Minimal, Complete and Verifiable example会让您更容易理解您的问题,但我想我明白您要做的是什么。对代码进行最少的修改,一个解决方案可能就是这样:

#include <iostream>
#include <string>

using namespace std;

string original = "xxxx, x xxxxx, xx x xxxxxx xxxxxxxx.";
string letters = "ThisIthinkisabetterquestion";
string desired = "This, I think, is a better question.";

int main()
{
    string fixed;
    int i, j;
    int originalSize = original.size();

    for(i=j=0; i < originalSize ;i++)
    {
        if(!isalnum(original[i]))
        {
          fixed += original[i];
        }
        else
        {
          fixed += letters[j++];
        }
    }
    cout << fixed << endl;
    cout << desired << endl;
    return 0;
}