Extract and print words separately from a given Camel Case string
Given a string in Camel Case format, we need to extract all the words which are present in the string.
CamelCase is the sequence of one or more than one words having the following properties:
- It is a concatenation of one or more words consisting of English letters.
- All letters in the first word are lowercase.
- For each of the subsequent words, the first letter is uppercase and the rest of the letters are lowercase.
Example:
Input: str = “GeeksForGeeks”
Output:
Geeks
For
GeeksInput: str = “AComputerSciencePortalForGeeks”
Output:
A
Computer
Science
Portal
For
Geeks
Approach:
A simple approach is to traverse the array and extract every word by looking at its first character, as it will always be in upper-case. Store all extracted words in a new array and print them.
C++
// C++ program to print words// from CamelCase String #include <cstring>#include <iostream>using namespace std; // Function to extract a wordchar* mystrtok(char* str){ static char* input = NULL; if (str != NULL) { input = str; } // Base case if (input == NULL) return NULL; // Array for storing tokens // +1 is for '\0' char* output = new char[strlen(input + 1)]; int i = 0; // Storing the upper case character output[i] = input[i]; i++; // Generating Tokens for (; input[i] != '\0'; i++) { if (!isupper(input[i])) output[i] = input[i]; else { output[i] = '\0'; input = input + i; return output; } } output[i] = '\0'; input = NULL; return output;} // Function to extract wordsvoid extractWords(char* s){ // Extract 1st word and print it char* ptr = mystrtok(s); cout << ptr << endl; // Extract the remaining words while (ptr != NULL) { ptr = mystrtok(NULL); cout << ptr << endl; }} // Driver codeint main(){ char s[] = "GeeksForGeeks"; extractWords(s); return 0;} |
Geeks For Geeks
Time Complexity: O(N)
Space Complexity: O(N), as we needed a new array to store output.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.



