#include #include using namespace std; /** * This programs demonstrates dynamically allocated arrays. */ /** * Returns an array that removes spaces from a c-string */ char* removeSpaces(const char s[]); /** * Counts the number of nonspace characters in an array */ int countNonSpaces(const char s[]); int main() { { char s[81] = "a man a plan a canal panama"; cout << endl; cout << "String : " << s << endl; cout << "No Spaces: " << removeSpaces(s) << endl << endl; } { char s[81] = "a beet skiddileote no wadda skadeet no wadda cachew"; cout << "String : " << s << endl; cout << "No Spaces: " << removeSpaces(s) << endl << endl; } } int countNonSpaces(const char s[]) { int count = 0; for (int i=0; s[i] != '\0';i++) { if (!isspace(s[i])) { count++; } } return count; } char* removeSpaces(const char s[]) { int count = countNonSpaces(s); char *spacesRemoved = new char[count+1]; int toIndex = 0; for (int fromIndex=0; s[fromIndex] != '\0';fromIndex++) { if (!isspace(s[fromIndex])) { spacesRemoved[toIndex] = s[fromIndex]; toIndex++; } } spacesRemoved[toIndex] = '\0'; return spacesRemoved; }