Use the first letter of each word

er 10 Write a word from Units 4-6 to match these meanings. The first letter of each word is given. 1 art lesson: a school subject which involves painting and drawing 2 b :you look through these to see things far away 3 coffein : it’s in coffee and tea and it makes you feel active : you make this when you decide to do something 5 e : a formal test 6 f drink: a drink with gas 7 8 : we play these (e.g. football, tennis) : students do this after school for 8h their teacher 9 i t : the subject of computers; what IT stands for 10 ____ f : food that isn’t healthy because it has lots of fat or sugar 11 first aid k : a bag of medicines, bandages, etc., to treat ill/injured people : books, poems, plays 12 1 13 m : a fast form of transport with two wheels 14 n_____________ :it’s got empty pages and you write notes in it 15 0 : connected to the internet 16 p. : a small round piece of medicine that you put in your mouth and swallow 17 r : a sport for which you have to wear special boots with wheels 18 s : a large boat that carries people or things across the sea : an electric street train 19 t :special clothes that students have 20 u to wear at school 21 V : potatoes, carrots, onions and peas are this type of food : clothes that don’t allow water to 22 w enter are this : an activity that helps relax the 23 y. body and mind​

1. There should be a stricter punishment for dropping litter. – Наказание за выброс мусора должно быть более строгим.
2. If someone shouts at you in public, you can take them to court. — Если кто-то кричит на вас в общественных местах, вы можете вызвать их в суд.
3. Do you know Sting’s song ‘If you love somebody, set them free’? — Вы знаете песню Стинга «Если ты любишь кого-то, освободи его»?
4. It always takes me hours to choose what I want to buy — I’m very indecisive. — У меня всегда занимает несколько часов, чтобы выбрать то, что я хочу купить — я очень нерешителен.
5. I have to buy special cosmetics because I have soft skin. — Я должен купить специальную косметику, потому что у меня мягкая кожа.
6. Most Hollywood films are quite predictable — you always know what’s going to happen. — Большинство голливудских фильмов вполне предсказуемы — вы всегда знаете, что произойдет.

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.

Examples: 

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

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

Source: https://www.geeksforgeeks.org/amazon-interview-set-8-2/

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 is true. And if we encounter any character other than space, we will check the boolean variable, if it was set as true as copy that charter to the output string and set the boolean variable as false. If the boolean variable is set false, do nothing. 

Algorithm: 

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.

Implementation:

C++

#include<bits/stdc++.h>

using namespace std;

string firstLetterWord(string str)

{

    string result = "";

    bool v = true;

    for (int i=0; i<str.length(); i++)

    {

        if (str[i] == ' ')

            v = true;

        else if (str[i] != ' ' && v == true)

        {

            result.push_back(str[i]);

            v = false;

        }

    }

    return result;

}

int main()

{

    string str = "geeks for geeks";

    cout << firstLetterWord(str);

    return 0;

}

Java

class GFG

{

    static String firstLetterWord(String str)

    {

        String result = "";

        boolean v = true;

        for (int i = 0; i < str.length(); i++)

        {

            if (str.charAt(i) == ' ')

            {

                v = true;

            }

            else if (str.charAt(i) != ' ' && v == true)

            {

                result += (str.charAt(i));

                v = false;

            }

        }

        return result;

    }

    public static void main(String[] args)

    {

        String str = "geeks for geeks";

        System.out.println(firstLetterWord(str));

    }

}

Python 3

def firstLetterWord(str):

    result = ""

    v = True

    for i in range(len(str)):

        if (str[i] == ' '):

            v = True

        elif (str[i] != ' ' and v == True):

            result += (str[i])

            v = False

    return result

if __name__ == "__main__":

    str = "geeks for geeks"

    print(firstLetterWord(str))

C#

using System;

class GFG

{

    static String firstLetterWord(String str)

    {

        String result = "";

        bool v = true;

        for (int i = 0; i < str.Length; i++)

        {

            if (str[i] == ' ')

            {

                v = true;

            }

            else if (str[i] != ' ' && v == true)

            {

                result += (str[i]);

                v = false;

            }

        }

        return result;

    }

    public static void Main()

    {

        String str = "geeks for geeks";

        Console.WriteLine(firstLetterWord(str));

    }

}

Javascript

<script>

    function firstLetterWord(str)

    {

        let result = "";

        let v = true;

        for (let i = 0; i < str.length; i++)

        {

            if (str[i] == ' ')

            {

                v = true;

            }

            else if (str[i] != ' ' && v == true)

            {

                result += (str[i]);

                v = false;

            }

        }

        return result;

    }

    let str = "geeks for geeks";

      document.write(firstLetterWord(str));

</script>

Time Complexity: O(n)
Auxiliary space: O(1). 

Approach 1 : Reverse Iterative Approach 

This is simplest approach to to getting first letter of every word of the string. In this approach we are using reverse iterative loop to get letter of words. If particular letter ( i ) is 1st letter of word or not is can be determined by checking pervious character that is (i-1). If the pervious letter is space (‘ ‘) that means (i+1) is 1st letter then we simply add that letter to the string. Except character at 0th position. At the end we simply reverse the string and function will return string which contain 1st letter of word of the string.

C++

#include <iostream>

using namespace std;

void get(string s)

{

    string str = "", temp = "";

    for (int i = s.length() - 1; i > 0; i--) {

        if (isalpha(s[i]) && s[i - 1] == ' ') {

            temp += s[i];

        }

    }

    str += s[0];

    for (int i = temp.length() - 1; i >= 0; i--) {

        str += temp[i];

    }

    cout << str << endl;

}

int main()

{

    string str = "geeks for geeks";

    string str2 = "Code of the    Day";

    get(str);

    get(str2);

    return 0;

}

Java

public class GFG {

    public static void get(String s)

    {

        String str = "", temp = "";

        for (int i = s.length() - 1; i > 0; i--) {

            if (Character.isLetter(s.charAt(i))

                && s.charAt(i - 1) == ' ') {

                temp

                    += s.charAt(i);

            }

        }

        str += s.charAt(0);

        for (int i = temp.length() - 1; i >= 0; i--) {

            str += temp.charAt(i);

        }

        System.out.println(str);

    }

    public static void main(String[] args)

    {

        String str = "geeks for geeks";

        String str2 = "Code of the    Day";

        get(str);

        get(str2);

    }

}

Python3

def get(s):

    str = ""

    temp = ""

    for i in range(len(s)-1, 0, -1):

        if s[i].isalpha() and s[i-1] == ' ':

            temp += s[i]

    str += s[0]

    for i in range(len(temp)-1, -1, -1):

        str += temp[i]

    print(str)

str = "geeks for geeks"

str2 = "Code of the    Day"

get(str)

get(str2)

Javascript

function get(s) {

  let str = "", temp = "";

  for (let i = s.length - 1; i > 0; i--) {

    if (s[i].match(/[a-zA-Z]/) && s[i - 1] === ' ') {

      temp += s[i];

    }

  }

  str += s[0];

  for (let i = temp.length - 1; i >= 0; i--) {

    str += temp[i];

  }

  console.log(str);

}

const str = "geeks for geeks";

const str2 = "Code of the    Day";

get(str);

get(str2);

Time Complexity: O(n)
Auxiliary space: O(1). 

Approach 2: Using StringBuilder

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 split strings are stored in an array of strings. Then we can simply append the first character of each split string in the String Builder object.  

Implementation:

C++

#include <bits/stdc++.h>

using namespace std;

string processWords(char *input)

{

    char *p;

    vector<string> s;

    p = strtok(input, " ");

    while (p != NULL)

    {

        s.push_back(p);

        p = strtok(NULL, " ");

    }

    string charBuffer;

    for (string values : s)

        charBuffer += values[0];

    return charBuffer;

}

int main()

{

    char input[] = "geeks for geeks";

    cout << processWords(input);

    return 0;

}

Java

class GFG

{

   private static StringBuilder charBuffer = new StringBuilder();

   public static String processWords(String input)

   {

        String s[] = input.split("(\s)+");

        for(String values : s)

        {

            charBuffer.append(values.charAt(0));

        }

      return charBuffer.toString();

   }

   public static void main (String[] args)

   {

      String input = "geeks for geeks";

      System.out.println(processWords(input));

   }

}

Python3

charBuffer = []

def processWords(input):

    s = input.split(" ")

    for values in s:

        charBuffer.append(values[0])

    return charBuffer

if __name__ == '__main__':

    input = "geeks for geeks"

    print(*processWords(input), sep = "")

C#

using System;

using System.Text;

class GFG

{

private static StringBuilder charBuffer = new StringBuilder();

public static String processWords(String input)

{

        String []s = input.Split(' ');

        foreach(String values in s)

        {

            charBuffer.Append(values[0]);

        }

    return charBuffer.ToString();

}

public static void Main()

{

    String input = "geeks for geeks";

    Console.WriteLine(processWords(input));

}

}

Javascript

<script>

var charBuffer = "";

function processWords(input)

{

        var s = input.split(' ');

        s.forEach(element => {

            charBuffer+=element[0];

        });

    return charBuffer;

}

var input = "geeks for geeks";

document.write( processWords(input));

</script>

Time Complexity: O(n)
Auxiliary space: O(1). 

Another Approach: Using boundary checker, refer https://www.geeksforgeeks.org/get-first-letter-word-string-using-regex-java/

This article is contributed by Aarti_Rathi and Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

The function below does not change any other part of the string than trying to convert all the first letters of all words (i.e. by the regex definition w+) to uppercase.

That means it does not necessarily convert words to Titlecase, but does exactly what the title of the question says: «Capitalize First Letter Of Each Word In A String — JavaScript»

  • Don’t split the string
  • determine each word by the regex w+ that is equivalent to [A-Za-z0-9_]+
    • apply function String.prototype.toUpperCase() only to the first character of each word.
function first_char_to_uppercase(argument) {
  return argument.replace(/w+/g, function(word) {
    return word.charAt(0).toUpperCase() + word.slice(1);
  });
}

Examples:

first_char_to_uppercase("I'm a little tea pot");
// "I'M A Little Tea Pot"
// This may look wrong to you, but was the intended result for me
// You may wanna extend the regex to get the result you desire, e.g., /[w']+/

first_char_to_uppercase("maRy hAd a lIttLe LaMb");
// "MaRy HAd A LIttLe LaMb"
// Again, it does not convert words to Titlecase

first_char_to_uppercase(
  "ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples"
);
// "ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples"

first_char_to_uppercase("…n1=orangesFromSPAIN&&n2!='a sub-string inside'");
// "…N1=OrangesFromSPAIN&&N2!='A Sub-String Inside'"

first_char_to_uppercase("snake_case_example_.Train-case-example…");
// "Snake_case_example_.Train-Case-Example…"
// Note that underscore _ is part of the RegEx w+

first_char_to_uppercase(
  "Capitalize First Letter of each word in a String - JavaScript"
);
// "Capitalize First Letter Of Each Word In A String - JavaScript"

Edit 2019-02-07: If you want actual Titlecase (i.e. only the first letter uppercase all others lowercase):

function titlecase_all_words(argument) {
  return argument.replace(/w+/g, function(word) {
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  });
}

Examples showing both:

test_phrases = [
  "I'm a little tea pot",
  "maRy hAd a lIttLe LaMb",
  "ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples",
  "…n1=orangesFromSPAIN&&n2!='a sub-string inside'",
  "snake_case_example_.Train-case-example…",
  "Capitalize First Letter of each word in a String - JavaScript"
];
for (el in test_phrases) {
  let phrase = test_phrases[el];
  console.log(
    phrase,
    "<- input phrasen",
    first_char_to_uppercase(phrase),
    "<- first_char_to_uppercasen",
    titlecase_all_words(phrase),
    "<- titlecase_all_wordsn "
  );
}

// I'm a little tea pot <- input phrase
// I'M A Little Tea Pot <- first_char_to_uppercase
// I'M A Little Tea Pot <- titlecase_all_words

// maRy hAd a lIttLe LaMb <- input phrase
// MaRy HAd A LIttLe LaMb <- first_char_to_uppercase
// Mary Had A Little Lamb <- titlecase_all_words

// ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples <- input phrase
// ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples <- first_char_to_uppercase
// Examplex: Camelcase/Uppercase&Lowercase,Exampley:N0=Apples <- titlecase_all_words

// …n1=orangesFromSPAIN&&n2!='a sub-string inside' <- input phrase
// …N1=OrangesFromSPAIN&&N2!='A Sub-String Inside' <- first_char_to_uppercase
// …N1=Orangesfromspain&&N2!='A Sub-String Inside' <- titlecase_all_words

// snake_case_example_.Train-case-example… <- input phrase
// Snake_case_example_.Train-Case-Example… <- first_char_to_uppercase
// Snake_case_example_.Train-Case-Example… <- titlecase_all_words

// Capitalize First Letter of each word in a String - JavaScript <- input phrase
// Capitalize First Letter Of Each Word In A String - JavaScript <- first_char_to_uppercase
// Capitalize First Letter Of Each Word In A String - Javascript <- titlecase_all_words

In this article we will discuss 5 different ways to convert first letter of each word in a string to uppercase. We will also discuss what are the limitations of each approach and which one is best for us.

Python Str class provides a member function title() which makes each word title cased in string. It means, it converts the first character of each word to upper case and all remaining characters of word to lower case.

Let’s use this to capitalize the first letter of each word in a string,

sample_text = "this is a sample string"

# Capitalize the first letter of each word i.e.
# Convert the first letter of each word to Upper case and all other to lower case
result = sample_text.title()

print(result)

Output:

Advertisements

This Is A Sample String

It worked fine with this solution, but there is a caveat. The title() function not only capitalize the first letter of each word in a string but also makes all remaining characters of each word to upper case. For example,

sample_text = "33a. it's GONE too far"

# Capitalize the first letter of each word
result = sample_text.title()

print(result)

Output:

33A. It'S Gone Too Far

There are 3 unexpected behaviors in above example,

  • In this example it converted “GONE” to “Gone”, because for each word in string it makes only first character as upper case and all remaining characters as lower case.
  • It converted “it’s” to “It’S” , because it considered “it’s” as two separate words.
  • It converted “33a” to “33A” , because it considered “a” as the first letter of word ’33a’.

So, title() function is not the best solution for capitalizing the first letter of each word in a string. Let’s discuss an another solution,

Use capitalize() to capitalize the first letter of each word in a string

Python’s Str class provides a function capitalize(), it converts the first character of string to upper case. Where as it is already in upper case then it does nothing.

We can use this capitalize() to capitalize the first letter of each word in a string. For that, we need to split our string to a list of words and then on each word in the list we need to call the capitalize() function. Then we need to join all the capitalized words to form a big string.

Let’s understand this with an example,

def capitalize_each_word(original_str):
    result = ""
    # Split the string and get all words in a list
    list_of_words = original_str.split()
    # Iterate over all elements in list
    for elem in list_of_words:
        # capitalize first letter of each word and add to a string
        if len(result) > 0:
            result = result + " " + elem.strip().capitalize()
        else:
            result = elem.capitalize()
    # If result is still empty then return original string else returned capitalized.
    if not result:
        return original_str
    else:
        return result

sample_text = "33a. it's GONE too far"

result = capitalize_each_word(sample_text)

print(result)

Output:

33a. It's Gone Too Far

It converted the first letter of each word in string to upper case.

Instead of writing the big function, we can achieve same using generator expressions i.e.

sample_text = "33a. it's GONE too far"

result = ' '.join(elem.capitalize() for elem in sample_text.split())

print(result)

Output:

33a. It's Gone Too Far

Here we split the string to words and iterated our each word in string using generator expression. While iterating, we called the capitalized() function on each word, to convert the first letter to uppercase and the joined that word to a string using ‘ ‘ as delimiter.

It served the purpose, but there can be one issue in this approach i.e. if words in original string are separated by more than one white spaces or tabs etc. Then this approach can cause error, because we are joining all capitalized words using same delimiter i.e. a single white space. Checkout this example,

sample_text = "this     is       a      sample   string"

result = ' '.join(elem.capitalize() for elem in sample_text.split())

print(result)

Output:

This Is A Sample String

Here original string had multiple spaces between words, but in our final string all capitalized words are separated by a single white space. For some this might not be the correct behavior. So, to rectify this problem checkout our next approach.

Using string.capwords() to capitalize the first letter of each word in a string

Python’s string module provides a function capwords() to convert the first letter to uppercase and all other remaining letters to lower case.
It basically splits the string to words and after capitalizing each word, joins them back using a given seperator. Checkout this example,

import string

sample_text = "it's gone tOO far"

result = string.capwords(sample_text)

print(result)

Output:

It's Gone Too Far

Problem with is solution is that it not only converts the first letter of word to uppercase but also makes the remaining letters of word to lower case. For some, this might not be the correct solution.

So, let’s discuss our final and best solution that does what’s only expected from it.

Using Regex to capitalize the first letter of each word in a string

Using regex, we will look for the starting character of each word and the convert to uppercase. For example,

import re

def convert_to_uupercase(m):
    """Convert the second group to uppercase and join both group 1 & group 2"""
    return m.group(1) + m.group(2).upper()

sample_text = "it's gone   tOO far"

result = re.sub("(^|s)(S)", convert_to_uupercase, sample_text)

print(result)

Output:

It's Gone   TOO Far

It capitalized only first character of each word in string and do not modifies the whitespaces between words.

How did it worked ?

We created use a pattern “(^|s)(S)”. It looks for string patterns that starts with zero or more whitespaces and then has a non whitespace character after that. Then for each matching instance, it grouped both initial whitespaces and the first character as separate groups. Using regex.sub() function, we passed each matching instance of the pattern to a function convert_to_uppercase(), which converts the second group i.e. first letter of word to upper case and then joins it with the first group(zero or more white spaces).

For string,

sample_text = "it's gone tOO far"

The function convert_to_uupercase() was called 4 times by regex.sub() and in each call group 1 & 2 of match object were,

'' and 'i'
' ' and 'g'
' ' and 't'
' ' and 'f'

Inside convert_to_uupercase(), it converted the second group i.e. first character of each word to uppercase.

So, this is how we can capitalize the first letter of each word in a string using regex and without affecting any other character of the string.

The complete example is as follows,

import string
import re


def capitalize_each_word(original_str):
    result = ""
    # Split the string and get all words in a list
    list_of_words = original_str.split()
    # Iterate over all elements in list
    for elem in list_of_words:
        # capitalize first letter of each word and add to a string
        if len(result) > 0:
            result = result + " " + elem.strip().capitalize()
        else:
            result = elem.capitalize()
    # If result is still empty then return original string else returned capitalized.
    if not result:
        return original_str
    else:
        return result


def main():

    print('*** capitalize the first letter of each word in a string ***')

    print('*** Use title() to capitalize the first letter of each word in a string ***')

    print('Example 1:')
    sample_text = "this is a sample string"
    # Capitalize the first letter of each word i.e.
    # Convert the first letter of each word to Upper case and all other to lower case
    result = sample_text.title()

    print(result)

    print('Example 2:')

    sample_text = "33a. it's GONE too far"

    # Capitalize the first letter of each word
    result = sample_text.title()

    print(result)

    print('*** Use capitalize() to capitalize the first letter of each word in a string ***')

    sample_text = "33a. it's GONE too far"

    result = capitalize_each_word(sample_text)

    print(result)

    print('Using capitalize() and generator expression')

    result = ' '.join(elem.capitalize() for elem in sample_text.split())

    print(result)

    print('Example 2:')

    sample_text = "this     is       a      sample   string"

    result = ' '.join(elem.capitalize() for elem in sample_text.split())

    print(result)

    print('*** Using string.capwords() to capitalize the first letter of each word in a string ***')

    sample_text = "it's gone tOO far"

    result = string.capwords(sample_text)

    print(result)

    print('*** Using Regex to capitalize the first letter of each word in a string ***')

    sample_text = "it's gone   tOO far"

    result = re.sub("(^|s)(S)", convert_to_uupercase, sample_text)

    print(result)

def convert_to_uupercase(m):
    """Convert the second group to uppercase and join both group 1 & group 2"""
    return m.group(1) + m.group(2).upper()

if __name__ == '__main__':
    main()

Output:

*** capitalize the first letter of each word in a string ***
*** Use title() to capitalize the first letter of each word in a string ***
Example 1:
This Is A Sample String
Example 2:
33A. It'S Gone Too Far
*** Use capitalize() to capitalize the first letter of each word in a string ***
33a. It's Gone Too Far
Using capitalize() and generator expression
33a. It's Gone Too Far
Example 2:
This Is A Sample String
*** Using string.capwords() to capitalize the first letter of each word in a string ***
It's Gone Too Far
*** Using Regex to capitalize the first letter of each word in a string ***
It's Gone   TOO Far

Понравилась статья? Поделить с друзьями:
  • Use of word dad
  • Use the find function in excel
  • Use of word contrary
  • Use the correct word vitamin spices infections
  • Use of word compromise