Sunday, September 22, 2024
Google search engine
HomeData Modelling & AIExtract and print words separately from a given Camel Case string

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:

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




// 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;
}


Java




// Java program to print words
// from CamelCase Stringimport java.util.*;
class Main {
 
  // Function to extract a word
  public static String mystrtok(String str, String[] input) {
    if (str != null) {
      input[0] = str;
    }
 
    // Base case
    if (input[0] == null)
      return null;
 
    // Array for storing tokens
    // +1 is for '\0'
    String output = "";
 
    int i = 0;
 
    // Storing the upper case character
    output += input[0].charAt(i);
    i++;
 
    // Generating Tokens
    for (; i < input[0].length(); i++) {
      if (!Character.isUpperCase(input[0].charAt(i)))
        output += input[0].charAt(i);
      else {
        output += '\0';
        input[0] = input[0].substring(i);
        return output;
      }
    }
 
    input[0] = null;
    return output;
  }
 
  // Function to extract words
  public static void extractWords(String s) {
 
    // Extract 1st word and print it
    String[] input = new String[1];
    String ptr = mystrtok(s, input);
    System.out.println(ptr);
 
    // Extract the remaining words
    while (ptr != null) {
      ptr = mystrtok(null, input);
      if(ptr != null)
        System.out.println(ptr);
    }
  }
 
  // Driver code
  public static void main(String[] args) {
    String s = "GeeksForGeeks";
    extractWords(s);
  }
}
 
// This code is contributed by rishabmalhdijo


Python




def my_strtok(s, input):
    if s is not None:
        input[0] = s
 
    if input[0] is None:
        return None
 
    output = ""
    i = 0
 
    output += input[0][i]
    i += 1
 
    while i < len(input[0]):
        if not input[0][i].isupper():
            output += input[0][i]
        else:
            output += '\0'
            input[0] = input[0][i:]
            return output
        i += 1
 
    input[0] = None
    return output
 
def extract_words(s):
    input = [None]
    ptr = my_strtok(s, input)
    print(ptr)
 
    while ptr is not None:
        ptr = my_strtok(None, input)
        if ptr is not None:
            print(ptr)
 
# Driver code
if __name__ == "__main__":
    s = "GeeksForGeeks"
    extract_words(s)


Output

Geeks
For
Geeks

Time Complexity: O(N) 
Auxiliary Space: O(N), as we needed a new array to store the output.

Using Regular Expression:

Java




/*package whatever //do not write package name here */
 import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
      // CamelCase String that you want to split
        String str = "GeeksForGeeks";
        for (
            String w : str.split(
                "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) {
            System.out.println(w);
        }
    }
}


Python




# Python program to print words
# from CamelCase String
import re
 
# Function to extract a word
def split_camel_case(identifier):
    matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier)
    return [m.group(0) for m in matches]
 
# Driver Code
print(split_camel_case("GeeksForGeeks"))
 
# This code is contributed by adityasha4x71


C#




// C# program for the above approach
using System;
 
public class GFG {
    public static void Main(string[] args) {
        // CamelCase String that you want to split
        string str = "GeeksForGeeks";
        foreach (string w in System.Text.RegularExpressions.Regex.Split(str, "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) {
            Console.WriteLine(w);
        }
    }
}
// This code is contributed by sdeadityasharma


Javascript




// JavaScript program to print words
// from CamelCase String
 
// Function to extract a word
function splitCamelCase(identifier) {
    return identifier.match(/.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)/g);
}
 
// Driver Code
console.log(splitCamelCase("GeeksForGeeks"));


Output

Geeks
For
Geeks

Time Complexity: O(N) 
Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments