📌  相关文章
📜  包含给定字符串中每个单词的第一个字母的字符串,带有空格

📅  最后修改于: 2022-05-13 01:57:08.567000             🧑  作者: Mango

包含给定字符串中每个单词的第一个字母的字符串,带有空格

字符串str包含小写英文字母和空格。它可能包含多个空格。获取每个单词的第一个字母并将结果作为字符串返回。结果不应包含任何空格。

例子:

Input : str = "geeks for geeks"
Output : gfg

Input : str = "happy   coding"
Output : hc

资料来源:https://www.geeksforgeeks.org/amazon-interview-set-8-2/

这个想法是遍历字符串str 的每个字符并维护一个布尔变量,该变量最初设置为 true。每当我们遇到空格时,我们将布尔变量设置为 true。如果我们遇到除空格以外的任何字符,我们将检查布尔变量,如果它被设置为 true,则将该宪章复制到输出字符串并将布尔变量设置为 false。如果布尔变量设置为 false,则什么也不做。
算法:

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.
C++
// C++ program to find the string which contain
// the first character of each word of another
// string.
#include
using namespace std;
 
// Function to find string which has first
// character of each word.
string firstLetterWord(string str)
{
    string result = "";
 
    // Traverse the string.
    bool v = true;
    for (int i=0; i


Java
// Java program to find the string which
// contain the first character of each word 
// of another string.
 
class GFG
{
     
    // Function to find string which has first
    // character of each word.
    static String firstLetterWord(String str)
    {
        String result = "";
 
        // Traverse the string.
        boolean v = true;
        for (int i = 0; i < str.length(); i++)
        {
            // If it is space, set v as true.
            if (str.charAt(i) == ' ')
            {
                v = true;
            }
             
            // Else check if v is true or not.
            // If true, copy character in output
            // string and set v as false.
            else if (str.charAt(i) != ' ' && v == true)
            {
                result += (str.charAt(i));
                v = false;
            }
        }
 
        return result;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str = "geeks for geeks";
        System.out.println(firstLetterWord(str));
    }
}
 
// This code is contributed by
// 29AjayKumar


Python 3
# Python 3 program to find the string which
# contain the first character of each word
# of another string.
 
# Function to find string which has first
# character of each word.
def firstLetterWord(str):
 
    result = ""
 
    # Traverse the string.
    v = True
    for i in range(len(str)):
         
        # If it is space, set v as true.
        if (str[i] == ' '):
            v = True
 
        # Else check if v is true or not.
        # If true, copy character in output
        # string and set v as false.
        elif (str[i] != ' ' and v == True):
            result += (str[i])
            v = False
 
    return result
 
# Driver Code
if __name__ == "__main__":
     
    str = "geeks for geeks"
    print(firstLetterWord(str))
 
# This code is contributed by ita_c


C#
// C# program to find the string which
// contain the first character of each word
// of another string.
using System;
 
class GFG
{
     
    // Function to find string which has first
    // character of each word.
    static String firstLetterWord(String str)
    {
        String result = "";
 
        // Traverse the string.
        bool v = true;
        for (int i = 0; i < str.Length; i++)
        {
            // If it is space, set v as true.
            if (str[i] == ' ')
            {
                v = true;
            }
             
            // Else check if v is true or not.
            // If true, copy character in output
            // string and set v as false.
            else if (str[i] != ' ' && v == true)
            {
                result += (str[i]);
                v = false;
            }
        }
        return result;
    }
 
    // Driver code
    public static void Main()
    {
        String str = "geeks for geeks";
        Console.WriteLine(firstLetterWord(str));
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript


C++
// C++ implementation of the above approach
#include 
using namespace std;
 
string processWords(char *input)
{
    /* we are splitting the input based on
    spaces (s)+ : this regular expression
    will handle scenarios where we have words
    separated by multiple spaces */
    char *p;
    vector s;
 
    p = strtok(input, " ");
    while (p != NULL)
    {
        s.push_back(p);
        p = strtok(NULL, " ");
    }
 
    string charBuffer;
 
    for (string values : s)
 
        /* charAt(0) will pick only the first character
        from the string and append to buffer */
        charBuffer += values[0];
 
    return charBuffer;
}
 
// Driver code
int main()
{
    char input[] = "geeks for geeks";
    cout << processWords(input);
    return 0;
}
 
// This code is contributed by
// sanjeev2552


Java
// Java implementation of the above approach
 
class GFG
{
   private static StringBuilder charBuffer = new StringBuilder();
     
   public static String processWords(String input)
   {
        /* we are splitting the input based on
           spaces (s)+ : this regular expression
           will handle scenarios where we have words
           separated by multiple spaces */
        String s[] = input.split("(\\s)+");
         
        for(String values : s)
        {
           /* charAt(0) will pick only the first character
              from the string and append to buffer */
            charBuffer.append(values.charAt(0));
        }
         
      return charBuffer.toString();
   }
    
   // main function
   public static void main (String[] args)
   {
      String input = "geeks for       geeks geeks      for geeks";
      System.out.println(processWords(input));
   }
}
 
// This code is contributed by Goutam Das


Python3
# 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[0])
    return charBuffer
 
# Driver Code
if __name__ == '__main__':
    input = "geeks for geeks"
    print(*processWords(input), sep = "")
 
# This code is contributed
# by SHUBHAMSINGH10


C#
// C# implementation of above approach
using System;
using System.Text;
 
class GFG
{
 
private static StringBuilder charBuffer = new StringBuilder();
     
public static String processWords(String input)
{
        /* we are splitting the input based on
        spaces (s)+ : this regular expression
        will handle scenarios where we have words
        separated by multiple spaces */
        String []s = input.Split(' ');
         
        foreach(String values in s)
        {
             
            /* charAt(0) will pick only the first character
            from the string and append to buffer */
            charBuffer.Append(values[0]);
        }
         
    return charBuffer.ToString();
}
     
// Driver code
public static void Main()
{
    String input = "geeks for geeks";
    Console.WriteLine(processWords(input));
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:

gfg

时间复杂度: O(n)

另一种方法1

这种方法使用Java的 StringBuilder 类。在这种方法中,我们将首先根据空格分割输入字符串。可以使用正则表达式匹配字符串中的空格。拆分字符串存储在字符串数组中。然后我们可以简单地将每个拆分字符串的第一个字符附加到 String Builder 对象中。

C++

// C++ implementation of the above approach
#include 
using namespace std;
 
string processWords(char *input)
{
    /* we are splitting the input based on
    spaces (s)+ : this regular expression
    will handle scenarios where we have words
    separated by multiple spaces */
    char *p;
    vector s;
 
    p = strtok(input, " ");
    while (p != NULL)
    {
        s.push_back(p);
        p = strtok(NULL, " ");
    }
 
    string charBuffer;
 
    for (string values : s)
 
        /* charAt(0) will pick only the first character
        from the string and append to buffer */
        charBuffer += values[0];
 
    return charBuffer;
}
 
// Driver code
int main()
{
    char input[] = "geeks for geeks";
    cout << processWords(input);
    return 0;
}
 
// This code is contributed by
// sanjeev2552

Java

// Java implementation of the above approach
 
class GFG
{
   private static StringBuilder charBuffer = new StringBuilder();
     
   public static String processWords(String input)
   {
        /* we are splitting the input based on
           spaces (s)+ : this regular expression
           will handle scenarios where we have words
           separated by multiple spaces */
        String s[] = input.split("(\\s)+");
         
        for(String values : s)
        {
           /* charAt(0) will pick only the first character
              from the string and append to buffer */
            charBuffer.append(values.charAt(0));
        }
         
      return charBuffer.toString();
   }
    
   // main function
   public static void main (String[] args)
   {
      String input = "geeks for       geeks geeks      for geeks";
      System.out.println(processWords(input));
   }
}
 
// This code is contributed by Goutam Das

Python3

# 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[0])
    return charBuffer
 
# Driver Code
if __name__ == '__main__':
    input = "geeks for geeks"
    print(*processWords(input), sep = "")
 
# This code is contributed
# by SHUBHAMSINGH10

C#

// C# implementation of above approach
using System;
using System.Text;
 
class GFG
{
 
private static StringBuilder charBuffer = new StringBuilder();
     
public static String processWords(String input)
{
        /* we are splitting the input based on
        spaces (s)+ : this regular expression
        will handle scenarios where we have words
        separated by multiple spaces */
        String []s = input.Split(' ');
         
        foreach(String values in s)
        {
             
            /* charAt(0) will pick only the first character
            from the string and append to buffer */
            charBuffer.Append(values[0]);
        }
         
    return charBuffer.ToString();
}
     
// Driver code
public static void Main()
{
    String input = "geeks for geeks";
    Console.WriteLine(processWords(input));
}
}
 
// This code is contributed by Rajput-Ji

Javascript


输出:

gfg

另一种方法2

使用边界检查器,请参阅 https://www.geeksforgeeks.org/get-first-letter-word-string-using-regex-java/