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++ 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 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 |
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)
|
using System;
using System.Text;
class MainClass
{ // Function to extract words
public static void ExtractWords( string s)
{
if ( string .IsNullOrEmpty(s))
{
Console.WriteLine( "Input string is empty or null." );
return ;
}
StringBuilder word = new StringBuilder();
// Iterate through each character in the string
for ( int i = 0; i < s.Length; i++)
{
// Check if the current character is uppercase
if ( char .IsUpper(s[i]))
{
// Print the word if it's not empty
if (word.Length > 0)
{
Console.WriteLine(word);
word.Clear();
}
}
// Append the current character to the word
word.Append(s[i]);
}
// Print the last word
if (word.Length > 0)
{
Console.WriteLine(word);
}
}
// Driver code
public static void Main( string [] args)
{
string s = "GeeksForGeeks" ;
ExtractWords(s);
}
} |
function myStrtok(s, input) {
// Set the initial string to process
if (s !== null ) {
input[0] = s;
}
// Return null if the input string is empty
if (input[0] === null ) {
return null ;
}
let output = "" ;
let i = 0;
output += input[0][i];
i++;
while (i < input[0].length) {
// If the character is not uppercase, continue appending it to the output
if (!input[0][i].match(/[A-Z]/)) {
output += input[0][i];
} else {
// If the character is uppercase, append '\0' to the output
output += '\0' ;
// Update the input string to process the rest of the string and return the output
input[0] = input[0].substring(i);
return output;
}
i++;
}
// If the loop completes, set the input to null and return the output
input[0] = null ;
return output;
} function extractWords(s) {
// Initialize input array
let input = [ null ];
// Get the first token
let ptr = myStrtok(s, input);
// Log the first token
console.log(ptr);
// Continue extracting and logging tokens until there are none left
while (ptr !== null ) {
ptr = myStrtok( null , input);
if (ptr !== null ) {
console.log(ptr);
}
}
} // Driver code let s = "GeeksForGeeks" ;
// Start extracting words from the string extractWords(s); |
Geeks For Geeks
Time Complexity: O(N)
Auxiliary Space: O(N), as we needed a new array to store the output.
Using Regular Expression:
#include <iostream> #include <regex> using namespace std;
int main() {
string str = "GeeksForGeeks" ;
regex camelCaseRegex( "([a-z])([A-Z])" );
string result = regex_replace(str, camelCaseRegex, "$1 $2" );
// Print each word on a new line
for ( char c : result) {
if (c != ' ' )
cout << c;
else
cout << "\n" ;
}
return 0;
} |
/*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 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# 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 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)