wwgywl 发表于 2016-9-21 15:39:29

C++ char* 空格分隔字符串


越是简单的东西越容易出错。

vector test;
//char* p="test data    ha   32ha.";
char *p = "12 23 56 78 99";
char* memory=p;
while (memory!=NULL)
{
while(*memory == ' ')
memory += 1;
char a={0};
char* temp=strstr(memory," ");

if(temp == NULL && memory != NULL){
memcpy(a,memory,strlen(memory));
test.push_back(a);
}
if (temp==NULL)
    break;

memcpy(a,memory,temp-memory);
test.push_back(a);
while(*temp==' ')
    temp++;
memory=temp;
}
cout<<test.size()<<endl;
vector::iterator Iter;
for (Iter=test.begin(); Iter!=test.end(); Iter++)
{
cout<<*Iter<<endl;
}

整个程序是在百度空间里看到的。但是那个程序存在问题,对于字符串以空格开头的字符串就无法处理了。并且,在处理完字符串之后并没有将最后一个字符串加入到vector中。
页: [1]
查看完整版本: C++ char* 空格分隔字符串