# Capitalize first letter of each word of input

This is a relatively quick one, but I'm sure you'll like it.

Codegolf a program that will take input in the form of a sentence and then provide the output with the first letter capitalized in each word.

Rules:

1. Submissions may not be in the form of a function. So no:

function x(y){z=some_kind_of_magic(y);return z;} as your final answer... Your code must show that it takes input, and provides output.

2. The code must preserve any other capital letters the input has. So

eCommerce and eBusiness are cool, don't you agree, Richard III?


will be rendered as

ECommerce And EBusiness Are Cool, Don't You Agree, Richard III?

3. Some of you may be thinking, "Easy, I'll just use regex!" and so using the native regex in your chosen golfing language will incur a 30 character penalty which will be applied to your final code count. Evil laugh

4. A "word" in this case is anything separated by a space. Therefore palate cleanser is two words, whereas pigeon-toed is considered one word. if_you_love_her_then_you_should_put_a_ring_on_it is considered one word. If a word starts with a non-alphabetical character, the word is preserved, so _this after rendering remains as _this. (Kudos to Martin Buttner for pointing this test case out).

• 4b. There is no guarantee that words in the input phrase will be separated by a single space.

Input:

eCommerce rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye


Output:

ECommerce Rocks. CrazyCamelCase Stuff. _those  Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye

6. This is code golf, shortest code wins...

Good luck...

• What about spaces at the end of the line? Do we have to preserve them? Can we add one if it serves our needs? – Dennis May 11 '15 at 0:48
• Dennis, please preserve spaces from the input... – WallyWest May 11 '15 at 1:04
• != TitleCase dam it! c# loses AGAIN! – Ewan May 11 '15 at 11:07
• @Tim The double space before Pigeon-toed is correct. He said to preserve spacing. – mbomb007 May 11 '15 at 17:04
• What separates the words? Any whitespace (tabs, newlines, etc) or just spaces? – Steven Rumbalski May 11 '15 at 18:22

# Java, 201178 174 bytes

class C{public static void main(String[]a){for(String s:a[0].split(" ")){int c=s.length()>0?s.charAt(0):0;System.out.print((c>96&c<123?(char)(c-32)+s.substring(1):s)+" ");}}}


I'm back after realizing that my previous program did not preserve spaces.

First time I've had to submit an entire class before. Pass in the string as a command-line argument wrapped in quotes. (I never thought I could get it this short!)

# Python 2, 6459 63

Try it here

This iterates through each word, converting the first character of each to uppercase, then printing it with a space after. I have to check if the split substring is not empty, which refers to multiple spaces in a row.

for w in raw_input().split(" "):print w and w[0].upper()+w[1:],

• @StevenRumbalski Fixed. – mbomb007 May 11 '15 at 20:41
• I think you can do w and w[0].upper()+w[1:]. Not sure about the input format though. – Sp3000 May 11 '15 at 23:56
• @StevenRumbalski Fixed – mbomb007 May 12 '15 at 16:44

Python 3, 58 63 59 chars

print(*(c and c[0].upper()+c[1:] for c in input().split(" ")))


I have to add 5 characters because of bugfix

• This not preserves multiple whitespaces. – manatwork May 12 '15 at 8:03

# Python 3, 101 bytes

x=list(' '+input())
for i in range(len(x)-1):
if x[i-1]==' ':x[i]=x[i].title()
print(''.join(x[1:]))


# R, 96 93

A different approach than Alex A's. I'm not using a loop, rather creating a another vector with a space prepended, then uppercasing any character in the original vector that is sitting under a space.

p=(strsplit(readline(),''))[[1]];s=c(' ',p);p[e]=toupper(p[e<-s==' ']);cat(head(p,-1),sep='')


Doesn't beat the regexp version though.

Edit I love it when you learn something new. Replace p[-length(p)] with head(p,-1)

# JavaScript (SpiderMonkey 31 (1.8)) 63 70

// first version
// new version, thx @nderscore
[for(c of prompt(o=x=''))o+=x=x<'!'?c.toUpperCase():c],alert(o)

• Nice method! Here's -3 : [for(c of x=prompt(o=''))(o+=x?c.toUpperCase():c,x=c<'!')],alert(o) – nderscore May 11 '15 at 6:03
• I can't sleep... so it's -7 now : [for(c of prompt(o=x=''))o+=x=x<'!'?c.toUpperCase():c];alert(o) – nderscore May 11 '15 at 6:37
• @nderscore wow your inexhaustible. I'm sorry I never find a way to give back – edc65 May 11 '15 at 6:46
• I'm just happy to aid in the quest for the smallest possible JS solution :) – nderscore May 11 '15 at 6:48
• @Chiru agreed. And thanx for giving the exact version. – edc65 Aug 5 '15 at 17:09

# V, 5 (non-competing)

$òBvU  Try it online! Not too interesting. Just a direct port of my vim answer: $        #Move to the last character
ò       #Recursively
B      #Move back a WORD
vU    #Capitalize


# Java 8, 135 bytes

It's rare that I beat all the other answers that use the same language.

interface M{static void main(String[]a){int c=0;for(char i:a[0].toCharArray()){System.out.print(c==0?(i+"").toUpperCase():i);c=i-32;}}}


TIO

# Ruby: 46 characters

l=0
gets.chars{|c|l&&c.upcase!
l=c==" "
$><<c}  Sample run: bash-4.3$ ruby -e 'l=0;gets.chars{|c|l&&c.upcase!;l=c==" ";$><<c}' <<< 'eCommerce rocks. crazyCamelCase stuff. _those pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye' ECommerce Rocks. CrazyCamelCase Stuff. _those Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye  # PHP, 91+30 bytes Well, all the ideas were used. I had to resort to drastic measures and build a huge piece of code: <?=preg_replace_callback('@( |^)([a-z])@',function($a){return$a[1].($a[2]^' ');},$_GET[s]);  The only function it uses is to fetch the small letters, using regex. • Your regular expression has a minor glitch. Should be @( |^)([a-z])@ as currently not processes the first word. – manatwork May 11 '15 at 16:08 • @manatwork GODDAMN! I deleted the wrong char. Thanks a lot for the tip. I've fixed it now. Initially I had @( |$|^)([a-z])@, which didn't made sense to have the |$ there, but deleted the very important |^ by mistake. – Ismael Miguel May 11 '15 at 16:18 • Why not ucwords? – Jörg Hülsermann May 17 '17 at 18:30 • @JörgHülsermann Because of codegolf.stackexchange.com/a/49980/14732 and because of rule #1. – Ismael Miguel May 17 '17 at 18:49 # C#, 143138123 bytes class G{static void Main(string[]a){var l=' ';foreach(var c in a[0]){System.Console.Write(l==' '?char.ToUpper(c):c);l=c;}}}  Runs as a command line util. Will try and golf it down from here. Comments & critique encouraged! • Instead of using ' ' you can use the ascii integer equivalent - 32 - which will save you two bytes :) – ldam May 14 '15 at 13:07 # Java, 142 First post here as well, but found that the requirements are a one to one mapping to the way Java handles arguments. class X{public static void main(String[]s){for(String p:s){System.out.append(p.toUpperCase().charAt(0)).append(p,1,p.length()).append(' ');}}}  Unfortunately, because they are command line arguments, spaces are not preserved, and the offending words (don't) have to be quoted ("don't"). So while I didn't entirely meet all the criteria I just wanted to share a Java solution that's under 200 bytes. # Ruby(55) gets.chars.inject(' '){|c,d|print c<?!?d.upcase():d;d}  I know that a better ruby solution exits in an old answer, but I like this better. note:c<?! checks for chars that come before !, which are just control/whitespace. # Groovy - 69 t=args[0];t.eachWithIndex{c,i->print!i|t[i-1]==' '?c.toUpperCase():c}  # Rebol - 56 51 print map-each n split input" "[uppercase/part n 1]  The above works correctly with the test case and also with multiple whitespace input. An interesting (but longer!) alternative version would to use the parse dialect (not a regex!) which when golfed would come down to 65 chars: parse s: input [any [x: thru [" " | end] (uppercase/part x 1)]] print s  # KDB(Q), 30 bytes {@[x;0,1+where" "=-1_x;upper]}  # Explanation  -1_x / handle case where last char is space 1+where" "= / find index of space and shift by 1 0, / include the first char @[x; ;upper] / apply upper case { } / lambda  # Test q){@[x;0,1+where" "=-1_x;upper]}t "ECommerce Rocks. CrazyCamelCase Stuff. _those Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye"  # Jelly, 9 bytes (non-competing) ṣ⁶Œu1¦€j⁶  Try it online! ### How it works ṣ⁶Œu1¦€j⁶ Main link. Argument: s (string) ṣ⁶ Split s at spaces. € Each; map this over the chunks: 1¦ Apply this to the first character: Œu Uppercase. j⁶ Join, separating by spaces.  • It's non-competing anyways, so you could use K instead of j⁶. – Erik the Outgolfer Oct 27 '16 at 9:23 # GNU sed, 20 + 1 (-r flag) +30 (regex penalty) = 51 s/(^| +)(.)/\1\u\2/g  (thks @manatwork for helping me save 4 bytes) Usage : sed 's/$$^\|$$$$.$$/\1\u\2/g' <<< "eCommerce and eBusiness are cool, don't you agree, Richard III?"  • You have to add +30 penalty for using regular expression and +1 for the required -r option. By the way, no need to say [a-z] if you consume all spaces first: s/(^| +)(.)/\1\u\2/g – manatwork May 11 '15 at 9:56 • thanks -- Actually It seems (at last with GNU sed, that it dors not need the -r option) – dieter May 11 '15 at 10:06 • Grr! I felt something is not optimal there since I first read this. s/^.| +./\U&/g – manatwork May 11 '15 at 17:19 • Your code has 20 bytes + 1 byte for a required r flag, so 21 without the regex penalty. It's not allowed to change the code when running it, which is what you did when adding all those escape slashes. The -r flag is given just for that purpose. Please correct the title and usage or I will downvote. – seshoumara Sep 3 '16 at 10:49 • So I see usage still has a different code. I won't downvote as initially said, sorry for coming too strong at you last time. – seshoumara Sep 6 '16 at 19:08 # s-lang, 8 bytes + 30 = 38 c![[^ ]*  s-lang Procedure: • Capitalize the first letter of every range matched by the regex. • Any number of Every character not in Space. # Brachylog, 12 bytes ṇ₁{ụʰ|}ᵐ~ṇ₁w  Try it online!  w Print the input ṇ₁ split on spaces { }ᵐ with every word ʰ having its first letter ụ uppercased | (without failing on empty words) ~ṇ₁ and then joined by spaces.  If this was allowed to be a function which would normalize runs of spaces to just one space, it would only be two bytes shorter: ṇ₁{ụʰ}ˢ~ṇ₁. That would be another two bytes shorter if we'd figured out how to parse chained metapredicates (ṇ₁ụʰˢ~ṇ₁), but since handling runs of spaces requires the |, it doesn't actually matter for this challenge. # 05AB1E, 8 bytes #εćuì}ðý  Try it online. Explanation:" # # Split the (implicit) input-string by the space character # (multiple adjacent spaces will give empty items in the list) ε # Map each string to: ć # Extract the head; pop and push the remainder and head separately to the stack u # Uppercase the head ì # Prepend it in front of the remainder again }ðý # After the map: join by spaces (which is output implicitly as result)  # Java, 167 bytes public class G{public static void main(String[]e){for(String n:e[0].split(" ")){System.out.print(n.length()<1?"":n.substring(0,1).toUpperCase()+n.substring(1)+" ");}}}  Ungolfed: public class G { public static void main(String[] e) { for (String n: e[0].split(" ")) { System.out.print(n.length() < 1 ? "" : n.substring(0, 1).toUpperCase() + n.substring(1) + " "); } } }  • You don't need braces for the For(), and I think substring(0,1) can be charAt(0). – lirtosiast Aug 18 '15 at 15:37 • The public modifier before the class definition can be removed. – Yytsi Jun 20 '16 at 14:10 # Python 2, 51 bytes lambda s:' '.join(map(str.capitalize,s.split(' ')))  Try it online! ## JavaScript, (ES6 RegEx Replacer) 66 bytes alert(prompt().replace(/(^[A-Z])|(\s[A-Z])/gi,m=>m.toUpperCase())) # Perl 6, 35 bytes say slurp.split(" ")>>.tc.join(" ")  Try it online! • You can rempve the join and just stringify it instead. slurp can also be get since there won't be newlines. 24 bytes – Jo King May 6 '19 at 21:58 ## VTL-2, 89 bytes 1 B=A 2 A=$
3 A=A-(32*(((B=0)+(B=32))*(A>97)*(A<123
4 $=8*(1-(A=4 5$=B
6 #=1-(A=4


If I read the challenge right, input seems fairly flexible, so... This operates every time a character is input. Input is terminated by an EOT (CtrlD). Output is one character behind, so every time you input a character, the previous one will be output. This really confused my brain when I was entering the test case.

Line 1 is fairly obvious, it copies the value of B into A. It's fine to start the program from here because uninitialized variables are assumed to be 0. Line 2 takes a single character input from the terminal and assigns A to its ASCII value. Fairly straightforward so far. Line 3 is a bit of a doozy, but it translates to (keeping in mind that B is the previous character entered, and A is the character just entered) IF (B==NULL OR B==" ") AND (96 < A < 123) THEN A=A-32. Because \$ echoes, line 4 inserts a backspace character so long as A isn't EOT. Line 5 prints B, and line 6 is akin to IF A!=EOT THEN GOTO 1.