Print First Letter of Every Word in the String
Problem​
Given a string S, the task is to create a string with the first letter of every word in the string.
Examples:​
Example 1:
Input:
S = "geeks for geeks"
Output: gfg
Example 2:
Input:
S = "bad is good"
Output: big
Your task:​
You don't need to read input or print anything. Your task is to complete the function firstAlphabet() which takes string S as input parameter and returns a string that contains the first letter of every word in S.
- Expected Time Complexity:
- Expected Auxiliary Space:
Constraints:​
Solution​
Python​
def firstAlphabet(self, S):
words = S.split()
result = ""
for word in words:
result += word[0]
return result
Java​
String firstAlphabet(String S) {
String[] words = S.split("\\s+");
StringBuilder result = new StringBuilder();
for (String word : words) {
if (!word.isEmpty()) {
result.append(word.charAt(0));
}
}
return result.toString();
}
C++​
string firstAlphabet(string S) {
istringstream iss(S);
string word;
string result;
while (iss >> word) {
result += word[0];
}
return result;
}
C​
char* firstAlphabet(char S[]) {
char result[100000];
int result_index = 0;
int i = 0;
while (S[i] != '\0') {
while (isspace(S[i])) {
i++;
}
if (!isspace(S[i])) {
result[result_index++] = S[i];
}
while (S[i] != '\0' && !isspace(S[i])) {
i++;
}
}
result[result_index] = '\0';
char* final_result = (char*) malloc(strlen(result) + 1);
strcpy(final_result, result);
return final_result;
}
- Time Complexity:
- Auxiliary Space: