一个“字符串和指针相结合”的编程题,请高手赐教!
要求:先用一个指针指向这个字符串"zhongyuan da jia ting" 然后写一个程序使得有一个指针数组,使这个指针数组的指针分别指向"zhongyuan" "da" "jia" "ting",
也就是遇到字符串中的空格后,就将其存到另一个变量中,然后使指针数组中的指针指向变量,
完成后输出格式为 "zhongyuan" "da" "jia" "ting"
希望高手写个完整程序出来,请赐教!
#include <iostream> #include <vector> #include <cstring> #include <cctype> using namespace std; class SplitResult { public: SplitResult(char** a = 0, int c = 0) : array(a), count(c) {} ~SplitResult(); char** getArray() { return array; } int getCount() { return count; } private: char** array; int count; friend SplitResult* split(const char*, SplitResult*); }; SplitResult::~SplitResult() { for (int i = 0; i < count; ++i) delete array[i]; delete array; } SplitResult* split(const char*, SplitResult*); int main() { const char* str = "zhongyuan da jia ting"; SplitResult sr; int i; split(str, &sr); for (i = 0; i < sr.getCount(); ++i) cout << sr.getArray()[i] << " "; } SplitResult* split(const char* str, SplitResult* sr) { const char* p = str; const char* start; char** array; char* tmp; int length; int i; vector<char*> v; while (*p) { if (isalpha(*p)) { start = p; length = 0; while (isalpha(*p)) ++p, ++length; tmp = new char[length + 1]; tmp[length] = '\0'; v.push_back(strncpy(tmp, start, length)); } ++p; } array = new char*[v.size()]; for (i = 0; i < v.size(); ++i) array[i] = v[i]; sr->array = array; sr->count = v.size(); return sr; }