Related Articles

Related Articles

Extract and print words separately from a given Camel Case string
  • Last Updated : 26 Jun, 2020

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:

  1. It is a concatenation of one or more words consisting of English letters.
  2. All letters in the first word are lowercase.
  3. 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
Geeks

Input: 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to print words
// from CamelCase String
  
#include <cstring>
#include <iostream>
using namespace std;
  
// Function to extract a word
char* 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 words
void 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 code
int main()
{
  
    char s[] = "GeeksForGeeks";
    extractWords(s);
  
    return 0;
}

chevron_right


Output:

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :