0) It's generally a bad idea to mention C++0x if you're interested in a strict C solution ;)
1) a parameter declaration like '(char str[])' is exactly the same as one like '(char* str)'. For parameters, this is true even if you put a number between the square brackets. C (or C++) arrays aren't first-class types. You can't pass them around properly (except as members of a struct/class); you can only pass pointers. Sorry.
2) Printing the output is not very useful. Anyone who calls your function is probably going to want to
do something with the split strings. So
return them, and let the caller decide what to do with them. (In the documentation, you then have to explain that the caller is responsible for free()ing the returned strings, because they'll be dynamically allocated here, and you can't free them before the caller gets to use them.)
3) There's no reason to limit yourself to a specific number of characters here.
4) There's no reason to require a full-stop at the end of the phrase. There's a standard C library function that finds the length of strings. You ever heard of a "null terminator"? That's what they're there for: so the function
strlen() can look for it.
5) Just because the standard library abbreviates functions names is no reason for you to do so, though. There are old legacy reasons why the C library names are all so short.
6) Your existing code makes no effort to actually accumulate the found words. I'm guessing that you intended to add this later but were stumped by the array declaration? :)
7) Speaking of strlen(), there is also
strchr in the standard library for searching for a given character, and
strncpy to copy substrings.
Off the top of my head:
char** splitString(char* str) { int spaces = countCharStr(str, ' '); // There is one more word than the count of spaces, but we also have // to allow room for a null terminator on the result array, so that the // calling code can see how many strings there were. It could just call // countCharStr() itself, true; but why repeat that effort :) char** result = malloc(sizeof(char*) * (spaces + 2)); if (!result) { return NULL; } char** result_pos = result; char* begin = str; char* end = str + strlen(str); // If the string ends with a space, we should end up creating one // empty string ("") at the end. while (begin <= end) { char* end_of_word = strchr(str, ' ') || end; int len = end_of_word - begin; char* copy = malloc(len + 1); if (!copy) { while (result_pos != result) { free(--*result_pos); } free(result); return NULL; } strncpy(copy, begin, len); copy[len] = '\0'; *result_pos++ = copy; begin = end_of_word + 1; } assert(result_pos == result + spaces + 1); *result_pos = NULL; return result;}
You know, it's not too late to switch to C++ ;)