初来匝到,承蒙信任,升任版主。先出一题, 题意如下:
如原始 string 为 "abc, 5678, it, can, also, be, an, empty, string . "
经过程序处理后,应该取出
abc
5678
it
can
also
be
an
empty
string
也就是说,程序以逗号作为分割符号,对原始字符串取样,取出子字符串,并对最后的结束字符句号做出处理,如有句号,则扔掉它。子字符串的起始端应不为空格。
// here is my code.
#include <iostream> #include <string> using namespace std;
void get_my_strarray_from_the_sourcestr(string scr, string * str_array, char c) { int cnt = 0; int length = scr.size(); int index_left = 0; int index_right = 0; while(index_right<length) { for(int i = index_left; i<length; i++) { if(scr == ' ') index_left++; else break; }
index_right = index_left; if((index_right = scr.find(c, index_right))==string::npos) { index_right = 0; if((index_right = scr.find('.', index_right))==string::npos) index_right = length;
if(index_right<index_left) break; str_array[cnt].append(&scr[index_left], &scr[index_right]); break; } else { str_array[cnt].append(&scr[index_left], &scr[index_right]); cnt++; index_left = index_right+1; } } }
int main() { string scr("abc, 5678, it, can, also, be, an, empty, string . "); // string scr(" ");
char c = ',';
int cnt = 0; int index_left = 0; while((index_left = scr.find(c, index_left))!=string::npos) { index_left++; cnt++; } cnt++;
string * str_array = new string [cnt];
// get_my_strarray_from_the_sourcestr(scr, str_array, c); // the test for the empty string get_my_strarray_from_the_sourcestr(scr, str_array, c); // the test for a source string
for(int i = 0; i<cnt; i++) cout<<str_array<<endl;
delete [] str_array;
return 0; }
#include <iostream> #include <string> using namespace std;void get_my_strarray_from_the_sourcestr(string scr, string * str_array, char c) { int cnt = 0; int length = scr.size(); int index_left = 0; int index_right = 0; while(index_right<length) { for(int i = index_left; i<length; i++) { if(scr == ' ') index_left++; else break; }
index_right = index_left; if((index_right = scr.find(c, index_right))==string::npos) { index_right = 0; if((index_right = scr.find('.', index_right))==string::npos) index_right = length;
if(index_right<index_left) break; str_array[cnt].append(&scr[index_left], &scr[index_right]); break; } else { str_array[cnt].append(&scr[index_left], &scr[index_right]); cnt++; index_left = index_right+1; } } }
int main() { string scr(\"abc, 5678, it, can, also, be, an, empty, string . \"); // string scr(\" \");
char c = ',';
int cnt = 0; int index_left = 0; while((index_left = scr.find(c, index_left))!=string::npos) { index_left++; cnt++; } cnt++;
string * str_array = new string [cnt];
// get_my_strarray_from_the_sourcestr(scr, str_array, c); // the test for the empty string get_my_strarray_from_the_sourcestr(scr, str_array, c); // the test for a source string
for(int i = 0; i<cnt; i++) cout<<str_array<<endl;
delete [] str_array;
return 0; }