给定一个Camel Case格式的字符串,我们需要提取字符串中存在的所有单词。
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.
例子:
Input: str = “GeeksForGeeks”
Output:
Geeks
For
Geeks
Input: str = “AComputerSciencePortalForGeeks”
Output:
A
Computer
Science
Portal
For
Geeks
方法:
一个简单的方法是遍历数组并通过查看第一个字符提取每个单词,因为它总是大写的。将所有提取的单词存储在一个新数组中并打印出来。
C++
// C++ program to print words
// from CamelCase String
#include
#include
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;
}
输出:
Geeks
For
Geeks
时间复杂度: O(N)
空间复杂度: O(N),因为我们需要一个新数组来存储输出。
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live