A String str is given which contains lowercase English letters and spaces. It may contain multiple spaces. Get the first letter of every word and return the result as a string. The result should not contain any space.
Input : str = "geeks for geeks" Output : gfg Input : str = "happy coding" Output : hc
The idea is to traverse each character of string str and maintain a boolean variable, which was initially set as true. Whenever we encounter space we set the boolean variable as true. And if we encounter any character other than space, we will check boolean variable, if it was set as true then copy that charter to output string and set the boolean variable as false. If the boolean variable is set false, do nothing.
1. Traverse string str. And initialize a variable v as true. 2. If str[i] == ' '. Set v as true. 3. If str[i] != ' '. Check if v is true or not. a) If true, copy str[i] to output string and set v as false. b) If false, do nothing.
Time Complexity: O(n)
Another Approach 1:
This approach uses the StringBuilder class of Java. In this approach, we will first split the input string based on the spaces. The spaces in the strings can be matched using a regular expression. The splitted strings are stored in an array of string. Then we can simply append the first character of each splitted string in the String Builder object.
# An efficient Python3 implementation # of above approach charBuffer =  def processWords(input): """ we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces """ s = input.split(" ") for values in s: """ charAt(0) will pick only the first character from the string and append to buffer """ charBuffer.append(values) return charBuffer # Driver Code if __name__ == '__main__': input = "geeks for geeks" print(*processWords(input), sep = "") # This code is contributed # by SHUBHAMSINGH10
Another Approach 2:Using boundary checker, refer https://www.geeksforgeeks.org/get-first-letter-word-string-using-regex-java/
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.