Title String#8320

Title String (Editorial)

A letter is the first letter of a word in two cases:

In all other cases, the letter is inside a word and remains unchanged.

Spaces are not modified. Therefore, all gaps between words, including those consisting of several consecutive spaces, are preserved, and the output string coincides with the input string everywhere except for the first letters of the words.

To convert a lowercase Latin letter to uppercase, you can use the toupper function or subtract the difference '' - '' = from the character code: in the ASCII table, the codes of lowercase and uppercase Latin letters differ by exactly .

Since the string contains spaces, it must be read as a whole, for example, using the getline function in C++ or gets in C.

Algorithm implementation

Declare a string.

string s;

Read the input string.

getline(cin,s);

If the first character of the string is not a space, it should be converted to an uppercase letter.

if (s[0] != ' ') s[0] = toupper(s[0]);

If the current character is a letter and there is a space before it, this character should also be converted to uppercase.

  for(int i = 1; i < s.size(); i++)
    if (s[i] != ' ' && s[i-1] == ' ')
      s[i] = toupper(s[i]);

Print the resulting string.

cout << s << endl;

Java implementation

import java.util.*;

public class Main 
{
  public static void main(String[] args) 
  {
    Scanner con = new Scanner(System.in);
    char s[] = con.nextLine().toCharArray();
    if (s[0] != ' ') s[0] = Character.toUpperCase(s[0]); 
    
    for(int i = 1; i < s.length; i++)
      if (s[i] != ' ' && s[i-1] == ' ') 
        s[i] = Character.toUpperCase(s[i]);

    System.out.println(String.valueOf(s));
    con.close();
  }
}

Python implementation

Read the input string.

s = input()

The title() function is used to convert the first letter of each word in a string to uppercase, while the remaining letters are converted to lowercase.

Print the resulting string.

print(s.title())