Capitalize first letter of each word of input

34

6

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.
  5. Test Case, (please use to test your code):

    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...

WallyWest

Posted 2015-05-10T23:23:16.860

Reputation: 6 949

Oh crap, I was thinking of multiple spaces but forgot to mention it... I've updated the brief accordingly... The brief will be locked from this point forward. – WallyWest – 2015-05-10T23:42:57.910

1What about spaces at the end of the line? Do we have to preserve them? Can we add one if it serves our needs? – Dennis – 2015-05-11T00:48:39.247

2Dennis, please preserve spaces from the input... – WallyWest – 2015-05-11T01:04:28.137

3!= TitleCase dam it! c# loses AGAIN! – Ewan – 2015-05-11T11:07:38.440

@WallyWest I don't think there should be a at the end of the example output? Also a double spacebefore Pigeon-toed`? – Tim – 2015-05-11T16:19:15.003

1@Tim The double space before Pigeon-toed is correct. He said to preserve spacing. – mbomb007 – 2015-05-11T17:04:19.440

2What separates the words? Any whitespace (tabs, newlines, etc) or just spaces? – Steven Rumbalski – 2015-05-11T18:22:45.797

1Is this ASCII only or should the answer handle unicode? – Bakuriu – 2015-05-12T09:31:07.527

@StevenRumbalski just standard space (ASCII 32) – WallyWest – 2015-05-12T14:55:22.063

@Bakuriu At this point it's just standard ASCII... – WallyWest – 2015-05-12T14:55:57.943

Does ”Ascii only” mean that answers that correctly capitalize e.g. ä to Ä are incorrent? Such as this one: http://codegolf.stackexchange.com/questions/49950/capitalize-first-letter-of-each-word-of-input#answer-49956

– leo – 2015-05-13T08:39:41.427

1@leo: Reading the OP's comment in context, it says the code doesn't have to handle non-ASCII characters. I'd say that means behavior for non-ASCII letters is undefined. – Dennis – 2015-05-14T13:55:11.110

1

Not even an honorable mention for the 13-byte Perl solution?

– ThisSuitIsBlackNot – 2015-05-27T22:22:22.443

Honorable mention made! Nice work! – WallyWest – 2015-05-27T22:40:29.797

Answers

21

CJam, 15 13 bytes

Lq{_eu?_S-}/;

Try it online in the CJam interpreter.

Pseudocode

L             e# B := ""
 q            e# Q := input()
  {       }/  e# for C in Q:
   _eu?       e#     C := B ? C : uppercase(C)
       _S-    e#     B := string(C).strip(" ")
            ; e# discard(B)

All modified characters C are left on the stack and, therefore, printed when exiting.

Dennis

Posted 2015-05-10T23:23:16.860

Reputation: 196 637

3Damn this is clever. D: – Martin Ender – 2015-05-11T00:25:47.167

I have to agree, outgolfing someone by 4 chars in a codegolf language is a feat in itself... well done. – WallyWest – 2015-05-11T01:07:09.977

12

@WallyWest: Golfing languages can give the impression that they kinda golf themselves, but I assure you that they don't. TMTOWTDI is true for all languages and especially for those with a lot of built-ins. Sometimes you win, sometimes you lose and sometimes you feel like you've been hit by a truck.

– Dennis – 2015-05-11T01:30:48.207

13

CSS 2.1, 49

:after{content:attr(t);text-transform:capitalize}

Explanation:

  • The attr function takes the input from a t (text) HTML attribute.
  • The input is capitalized by setting text-transform to capitalize.
  • The output is provided as a generated content, using the content property on an ::after pseudo-element.

Runnable snippet:

:after {
    content: attr(t);
    text-transform: capitalize;
}
<div 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"></div>

Note: CSS 2.1 specified the desired behavior: capitalize uppercased the first character of each word. However, CSS3 uppercases first typographic letter unit of each word. So the snippet above won't work properly neither on old IE, which didn't follow CSS 2.1; nor on new compliant browsers which follow CSS3.

Oriol

Posted 2015-05-10T23:23:16.860

Reputation: 792

Oh, this is clever! – IQAndreas – 2015-05-12T06:28:28.600

1(too bad about the _those problem on CSS3 browsers, but I'm still upvoting because of the unique way of solving the problem.) – IQAndreas – 2015-05-12T06:29:50.367

@Oriol, "oh this is clever!" indeed! Sorry IQAndreas, I have to borrow your comment here... this is an ingenious approach to solving the problem... i will have to make use of this approach... – WallyWest – 2015-05-21T11:16:53.783

10

Javascript (ES6), 77 bytes

alert(prompt().split(' ').map(x=>x&&x[0].toUpperCase()+x.slice(1)).join(' '))

Commented

alert( // output
    prompt(). // take input
    split(' '). // split by spaces
    map(x=> // map function to array
        x && // if x, empty string "" is falsey and returns itself
        x[0].toUpperCase() + x.slice(1) // capaitalize 1st char and concatenate the rest
    ).
    join(' ') // join array with spaces
)

nderscore

Posted 2015-05-10T23:23:16.860

Reputation: 4 912

What happens if words are separated by multiple spaces? [4b] – Caek – 2015-05-11T02:35:34.157

3@Caek It's handled by the x&&. An empty string is falsey so the && short-circuits and returns the left operand, the empty string. Spaces are preserved. – nderscore – 2015-05-11T02:38:53.550

Awesome, thanks for the explanation. Might help me figure out how I can get it to work now. – Caek – 2015-05-11T02:49:36.610

This will capitalize even non Ascii characters, so that å will become Å! – leo – 2015-05-13T08:38:23.647

9

Perl, 13 bytes

perl -040pe '$_="\u$_"'

9 bytes plus 4 bytes for 040p (assuming I've interpreted the rules on special invocations correctly).

-040 sets the input record separator $/ to a single space, so spaces are preserved; the \u escape sequence converts the next character to title case.

ThisSuitIsBlackNot

Posted 2015-05-10T23:23:16.860

Reputation: 1 050

Great work, honorable mention for using the command line! – WallyWest – 2015-05-27T22:28:46.957

7

CJam, 17 15 bytes

lS/{S+(eu\+}/W<

Test it here.

Fairly straightforward implementation of the spec. Make use of the new {}& to avoid errors for consecutive spaces.

Two bytes saved by Dennis.

Martin Ender

Posted 2015-05-10T23:23:16.860

Reputation: 184 808

Great stuff! Is CJam primarily just a golfing language or does it have some practical commercial applications? – WallyWest – 2015-05-10T23:47:46.757

6@WallyWest No it's just a golfing language. It definitely doesn't have commercial applications, but I personally use it occasionally for quick throw-away scripts (because it has a lot of built-ins, and if you know what you're doing, then typing fewer characters is quicker than typing more characters ;)). – Martin Ender – 2015-05-10T23:49:28.393

You can save a few bytes by appending a space to each word. Depending on the OP's answer to my question, this could get you to either 14 or 12 bytes. – Dennis – 2015-05-11T00:58:46.963

@Dennis Oh right, I was playing around with that, but didn't consider simply adding it before pulling off the first character. I'll change that tomorrow, thank you! – Martin Ender – 2015-05-11T01:00:39.767

@Dennis Thanks, I changed it, but I'm not sure what 14-byte version you meant. If you're talking about omitting the second +, then that breaks if the input contains trailing spaces. – Martin Ender – 2015-05-11T09:02:12.550

Yes, I miscounted the spaces. :( – Dennis – 2015-05-11T13:19:41.707

7

Perl Version < 5.18, 30 27 26 25

say map"\u$_",split$,=$"

24 characters +1 for -n.

\u makes the next character in a string uppercase. @ThisSuitIsBlackNot pointed this out to save 1 byte. Before we were using the function ucfirst.

From the perldocs,

As another special case, split emulates the default behavior of the command line tool awk when the PATTERN is either omitted or a literal string composed of a single space character (such as ' ' or "\x20" , but not e.g. / / ). In this case, any leading whitespace in EXPR is removed before splitting occurs, and the PATTERN is instead treated as if it were /\s+/ ; in particular, this means that any contiguous whitespace (not just a single space character) is used as a separator. However, this special treatment can be avoided by specifying the pattern / / instead of the string " " , thereby allowing only a single space character to be a separator. In earlier Perls this special case was restricted to the use of a plain " " as the pattern argument to split, in Perl 5.18.0 and later this special case is triggered by any expression which evaluates as the simple string " " .

Since $" evaluates to a space, this will preserve the spaces. Since we want to both set $, to a space character, and input a space character to the split, @nutki pointed out we can do both as the input to the split. That saves 3 bytes from what we had before, which was first setting $, and then inputting $" to the split.

Using a , for map instead of {} saves an additional byte, as @alexander-brett pointed out.

Run with:

echo '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' | perl -nE'say map"\u$_",split$,=$"'

hmatt1

Posted 2015-05-10T23:23:16.860

Reputation: 3 356

1Save 1 byte with ...map"\u$_",split... – alexander-brett – 2015-05-12T15:19:13.067

@alexander-brett thanks! I updated the answer. – hmatt1 – 2015-05-12T16:51:04.677

7

C, 64 63 bytes

a;main(c){while(~(c=getchar()))putchar(a?c:toupper(c)),a=c-32;}

Fix: some compilers (such as Clang) don't like an int parameters in place of argv, so I moved it to a global variable. The byte count stays the same. Thanks to squeamish ossifrage for noticing. Down to 63 bytes, thanks Dennis.

Ungolfed:

int a;

int main(int c) {
    while(~(c = getchar()))
        putchar(a ? c : toupper(c)),
        a = c - ' ';
}

Pretty straightforward: if a is false, the character is converted to uppercase. It is set after reading a space: c - ' ' is false only if c == ' '. toupper() ignores everything that is not a lowercase letter, so symbols and multiple spaces are fine. -1 has all bits set, so when getchar() returns -1 the NOT operator makes it zero, and the loop stops. a is declared as a global variable, so it is initializd to zero (false). This ensures that the first word is capitalized.

Andrea Biondo

Posted 2015-05-10T23:23:16.860

Reputation: 1 452

1while(~(c=getchar()) — I like that. Clang won't actually compile this, but you can get the same character count with c;main(a){...} – r3mainer – 2015-05-11T13:24:05.177

1If you swap the declarations of a and c and the order of the ternary operator, you can replace == with - to save one byte. – Dennis – 2015-05-11T16:45:37.853

You are right, of course. – Andrea Biondo – 2015-05-11T17:10:03.017

Nice! +1 The program would work the same when using while(!(c = getchar())), right? – Spikatrix – 2015-05-13T11:17:08.380

1@Cool Guy: Nope, the bitwise ~ and the logical ! are not the same. In C anything that is not zero is considered true, so your condition would be like while((c = getchar()) == 0) which of course won't work. The bitwise NOT operator ~ negates the value bit-by-bit. To break the loop, ~c must be zero: this means that all bits have to be one, so that when negated they become all zeroes. That value (for a 32bit int) is 0xFFFFFFFF, which, if signed, is -1 (EOF). – Andrea Biondo – 2015-05-13T12:38:03.577

putchar(c>96?c&&95:c) //lowercase letters are 64 more than upper case letters, and begin at 97. this will do funny things to words begining with chars above 'z' – Andrew Hill – 2015-08-06T01:50:32.677

7

Python 3, 59 56 bytes

f=1
for c in input():print(end=f*c.upper()or c);f=c==" "

Thanks to @Reticality for 3 bytes.

Sp3000

Posted 2015-05-10T23:23:16.860

Reputation: 58 729

3How about print(end=f*c.upper()or c)? That would save 4 bytes – None – 2015-05-11T15:45:09.933

@Reticality Oh wow, I had no idea you could have an empty print with just a keyword arg. Thanks! – Sp3000 – 2015-05-11T23:01:04.287

5

JAVA, 273 bytes

EDIT

import static java.lang.System.*;class x{public static void main(String[] s){char[] a=new java.util.Scanner(in).nextLine().toCharArray();boolean f=1>0;for(int i=0;i<a.length;i++){if(a[i]==' '){f=1>0;continue;}if(f){a[i]=Character.toUpperCase(a[i]);f=1<0;}}out.println(a);}}

Atul Kumbhar

Posted 2015-05-10T23:23:16.860

Reputation: 151

This is my first answer in PCG, not sure if this is acceptable. – Atul Kumbhar – 2015-05-11T02:15:36.227

Welcome aboard! You might try removing whitespace and using single characters for variable names. There are some other tips for golfing JAVA as well.

– nderscore – 2015-05-11T02:19:10.040

Thanks @nderscore for the hint, I have edited my answer using the tips. – Atul Kumbhar – 2015-05-11T02:51:02.843

Looking better! I also added the byte count into your post for you. – nderscore – 2015-05-11T03:26:08.523

You can save a few by removing import java.util.*; and replacing Scanner with java.util.Scanner. – TNT – 2015-05-11T12:40:27.020

You can remove the spaces in f = 1>0;. – LegionMammal978 – 2015-05-11T20:15:57.483

Thanks guys for comment...answer updated as per your comments – Atul Kumbhar – 2015-05-12T00:04:47.493

The public keyword isn't necessary so that can save you 7 bytes. – Yytsi – 2016-06-20T07:44:41.513

1@TuukkaX He doesn't have public in front of the class.. And if you mean he can remove the public in front of the static void main(..., then you are wrong, unless he also changes the class to interface and uses Java 8+. – Kevin Cruijssen – 2016-06-20T13:01:28.020

@KevinCruijssen yup, my mistake! – Yytsi – 2016-06-20T14:09:24.980

5

><> (Fish), 39 bytes

</?-' 'o:;?(0:<-*' '*('{'$)'`'::i
i/.0e

Method:

  • Take one char and capitalize it if in range a-z then print it out. (left-to-right code for this part is i::'backquote')$'{'(*' '*+)
  • If the last taken char is an EOF char then exit else print it
  • If the last taken char is a space char then go to point 1 else take a new letter and go to point 2.

randomra

Posted 2015-05-10T23:23:16.860

Reputation: 19 909

5

JavaScript (regex solution) - 104 bytes

Someone has to bite the bullet and post the RegEx solution! 74 characters, plus the +30 character penalty:

alert(prompt().replace(/(^| )[a-z]/g,function(m){return m.toUpperCase()}))

Or if you want to read and understand the code in its non-compacted fashion:

//     Matches the (beginning of the line or a space), followed by a lowercase English character.  
string.replace( /(^| )[a-z]/g ,
                function(match) { return match.toUpperCase(); }

IQAndreas

Posted 2015-05-10T23:23:16.860

Reputation: 1 180

1Clever... though of course, you've paid the price with a 30 character penalty... I take my hat off to you for biting the bullet... – WallyWest – 2015-05-21T11:12:30.350

4

Python 2, 73 bytes

i=raw_input()
print''.join((c,c.upper())[p==' ']for p,c in zip(' '+i,i))

This program capitalises a letter if preceded by a space (with a kludge for the first character in the string). It relies on the .upper() string method to capitalise correctly.

Logic Knight

Posted 2015-05-10T23:23:16.860

Reputation: 6 622

2You could save 2 bytes by porting to Python 3. (-4 raw_input => input, +2 print => print()) – Steven Rumbalski – 2015-05-11T19:27:14.903

Thanks Steven. I had considered the savings in bytes by coding in Python 3. Then I thought, if I was to change language to be competitive, I would change to Pyth. I am happy to compete in the Python 2 sub-league. I code in Python 2 every day for work, so this experience makes me better at my job (but my work code is not golfed!). – Logic Knight – 2015-05-16T11:11:51.297

4

PHP 64 76 77 83 84 89 bytes

Does $_GET count as input in PHP?
If so, here is my first CG attempt

foreach(explode(' ',$_GET[@s])as$k=>$v)echo$k?' ':'',ucfirst($v)

Thanks manatwork :)

One could just use the ucwords function, which would result in 21 bytes:

<?=ucwords($_GET[@s])

thanks Harry Mustoe-Playfair :)

Octfx

Posted 2015-05-10T23:23:16.860

Reputation: 141

Personally I consider only fgets(STDIN) to read input. But we have no consensus on $_GET as far as I know. – manatwork – 2015-05-11T09:52:20.433

Yup, that works :D – Octfx – 2015-05-11T10:16:53.197

You don't need the tricks to shut up the warnings. Thei're warnings! Nobody cares about them. – Ismael Miguel – 2015-05-11T13:05:28.653

Well, didn't thought of that. Guess I'll have to stick to substr – Octfx – 2015-05-11T14:05:37.597

No need for that. It's just time to forget my earlier advice on removing $k=>. Put it back: foreach(split(' ',$_GET[@s])as$k=>$v)echo$k?' ':'',ucfirst($v); – manatwork – 2015-05-11T14:39:16.077

I didn't knew that you could echo multiple "things" with , Thanks :)
split() is deprecated as of PHP 5.3 so we have to use @ once again. But doesn't add split() +30 to the bytecount? Since it splits by regex
– Octfx – 2015-05-11T14:45:13.177

Not sure. I considered that split(' ') equivalent of splitting on string space as used in Perl, Ruby and JavaScript answers too. – manatwork – 2015-05-11T15:19:54.550

<?= ucwords($_GET[@s]) is one byte shorter! 22 – Harry Mustoe-Playfair – 2015-05-11T20:53:29.437

you do not even need the space between = and ucwords – Octfx – 2015-05-11T20:55:58.310

I think that $k?' ':'', can be changed into !$k?:' ',, which is 1 byte shorter. – Ismael Miguel – 2015-05-13T16:54:57.493

This won't work, because if $k evaluates to true it will return 1 which is then echoed – Octfx – 2015-05-13T17:13:13.387

4

Haskell, 69

import Data.Char
main=interact$tail.scanl(!)' '
' '!c=toUpper c;_!c=c

Explanation:

scanl takes a function (a -> b -> a) and an initial value a, then iterates over a list of [b]s to make a list of [a]s:

scanl (!) z [a,b,c] == [   z
                       ,   z ! a
                       ,  (z ! a) ! b
                       , ((z ! a) ! b) ! c]

It repeatedly takes the previous result as the left argument of the function passed to it, and a value from the input list as the right argument, to make the next one.

I wrote a function (!) :: Char -> Char -> Char that returns the right character you pass it, but capitalizes it if the left char is ' ' (space). For scanl, this means: return the value from the input list, but capitalize it if the previous result was a space. So scanl (!) ' ' "ab cd" becomes:

    scanl (!) ' ' "ab cd"
==> ' ' : scanl (!) (' ' ! 'a') "b cd"
==> ' ' : scanl (!)     'A'     "b cd"
==> ' ' : 'A' : scanl (!) ('A' ! 'b') " cd"
==> ' ' : 'A' : scanl (!)     'b'     " cd"
==> ' ' : 'A' : 'b' : scanl (!) ('b' ! ' ') "cd"
==> ' ' : 'A' : 'b' : scanl (!)     ' '     "cd"
==> ' ' : 'A' : 'b' : ' ' : scanl (!) (' ' ! 'c') "d"
==> ' ' : 'A' : 'b' : ' ' : scanl (!)     'C'     "d"
==> ' ' : 'A' : 'b' : ' ' : 'C' : scanl (!) ('C' ! 'd') ""
==> ' ' : 'A' : 'b' : ' ' : 'C' : scanl (!)     'd'     ""
==> ' ' : 'A' : 'b' : ' ' : 'C' : 'd' : ""
==> " Ab Cd"

We need the initial value ' ' to capitalize the first letter, but then we chop it off with tail to get our final result.

Lynn

Posted 2015-05-10T23:23:16.860

Reputation: 55 648

Nice! Can you please explain it for me? – poida – 2015-05-12T10:23:35.523

I wrote an explanation. – Lynn – 2015-05-12T15:06:15.680

Some more scanl examples: one, two.

– Lynn – 2015-05-12T15:14:58.537

@Mauris kudos for using such a great algorithmm like this... :) – WallyWest – 2015-05-21T11:11:30.437

3

Pyth, 20 bytes

uXGHr@GH1fqd@+dzTUzz

These multiple spaces really sucks. Otherwise there would have been a really easy 12 bytes solution.

Try it online: Pyth Compiler/Executor

Explanation

                      implicit: z = input string
         f       Uz   filter [0, 1, 2, ..., len(z)-1] for elements T, which satisfy:
          qd@+dzT        " " == (" " + z)[T]
                      (this finds all indices, which should be capitalized)
u                  z  reduce, start with G = z, for H in idices ^ update G by
 XGH                     replace the Hth char of G by
    r   1                upper-case of
     @GH                 G[H]
                      implicitly print result

edit: 16 chars is possible with @Dennis algorithm.

Jakube

Posted 2015-05-10T23:23:16.860

Reputation: 21 462

1The multiple space thing is there to make it a lot more challenging... otherwise it would be a simple case of string.split(" ") or something similar... But you've done well to do it in 20 characters – WallyWest – 2015-05-11T01:05:40.833

3

PHP: 76 74 characters

foreach($l=str_split(fgets(STDIN))as$c){echo$l?ucfirst($c):$c;$l=$c==" ";}

Sample run:

bash-4.3$ php -r 'foreach($l=str_split(fgets(STDIN))as$c){echo$l?ucfirst($c):$c;$l=$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

manatwork

Posted 2015-05-10T23:23:16.860

Reputation: 17 865

Instead of ucfirst($c), use $c^' '. (Tip: if you bitwise-xor a letter with a space, it will be converted from uppercase to lowercase, and the oposite applies too) – Ismael Miguel – 2015-05-12T15:50:43.177

@IsmaelMiguel, that works fine in your solution as you process only lowercase letters. But in my solution all first characters are processed. So for the (otherwise great) xor trick my code would also need some character type filtering. :( – manatwork – 2015-05-12T15:59:05.783

That didn't crossed my mind. There must be a bitwise trick to check if it is a letter or not. – Ismael Miguel – 2015-05-12T16:08:12.453

1One thing you can do is $l=str_split(fgets(STDIN)), which reduces the code by 2 bytes! – Ismael Miguel – 2015-05-12T17:10:45.823

1Now I'm going mad. Man, how long I starred to that initialization and missed it. Thank you, @IsmaelMiguel. – manatwork – 2015-05-12T17:14:34.347

You are welcome. I spent more than I should have ever spent to find something to shorten this. One thing you could do would be using as$l=>$c, but this way is 1 byte shorter. As an alternative to your fgets(STDIN), you can use $_GET[s] (it throws warnings, but ignore those or add @ before s). This way, it is still a standard input. And shorter. You save 4 bytes! – Ismael Miguel – 2015-05-12T17:22:52.997

3

JAVA, 204 211 226 bytes

My first entry on CG, I hope it's fine:

class U{public static void main(String[]s){int i=0;char[]r=s[0].toCharArray();r[0]=Character.toUpperCase(r[0]);for(char c:r){if(c==' '&&i>0)r[i+1]=Character.toUpperCase(r[i+1]);i++;System.out.print(c);}}}

Saved 7 bytes thanks to @TNT

Angelo Tricarico

Posted 2015-05-10T23:23:16.860

Reputation: 141

Involving my poor Java skills: public class U{public static void main(String[]s){int i=-1,j;char[]r=s[0].toCharArray();for(char c:r)if(++i==0||c==' '&&i>0)r[j=i+(i==0?0:1)]=Character.toUpperCase(r[j]);System.out.print(r);}} – manatwork – 2015-05-11T16:36:02.770

1Welcome to PPCG! The public modifier isn't necessary so you can save 7 more. – TNT – 2015-05-11T16:38:04.207

3

CJam, 14 bytes

It's not the shortest, but...

qS/Sf.{\eu}s1>

Another answer using similar ideas:

qS/Laf.{;eu}S*

.x only changes the first item if one of the parameters has only one item.

jimmy23013

Posted 2015-05-10T23:23:16.860

Reputation: 34 042

1Chaining f and . is pretty ingenious. Another 14 bytes variant: qS/Sf.{\eu}S.- – Dennis – 2015-05-12T15:44:43.967

3

Lua, 64 62 61 bytes

Lua is a horrendous language to golf in, so I'm pretty proud of myself for this one.

print(string.gsub(" "..io.read(),"%s%l",string.upper):sub(2))

[Try it here]1 Outdated, will update tommorow

user40734

Posted 2015-05-10T23:23:16.860

Reputation:

1Welcome to PPCG! Surely, you don't need those spaces after commas? – Martin Ender – 2015-05-11T23:59:18.037

Wow, I'm so new to this I didnt even know spaces counted. 62 bytes! – None – 2015-05-12T00:52:35.230

2I also just noticed it's not entirely correct: you are capitalising letters after all non-letters, so abc_def will give Abc_Def. However only letters after spaces should be turning into upper case. The good news is, fixing it saves a byte. ;) – Martin Ender – 2015-05-12T00:57:55.540

3

C, 74 bytes

a,b=1;main(){while((a=getchar())>0)b=isspace(putchar(b?toupper(a):a));}

Makes no assumptions about the run-time character set (ASCII, EBCDIC, Baudot, ...whatever). Does assume that EOF is negative (I think C guarantees that).

a,b=1;
main()
{
    while((a=getchar())>0)
        b=isspace(putchar(b?toupper(a):a));
}

a is the input character; b is true if the last character was space. The only non-obvious bit is that we use the fact that putchar returns the character printed if there's no error.

Toby Speight

Posted 2015-05-10T23:23:16.860

Reputation: 5 058

3

C# Linq - 187

This is nowhere close to winning but I just love Linq too much.

namespace System{using Linq;class P{static void Main(string[]a){Console.Write(a[0].Substring(1).Aggregate(a[0][0].ToString().ToUpper(),(b,c)=>b[b.Length-1]==32?b+char.ToUpper(c):b+c));}}}

ldam

Posted 2015-05-10T23:23:16.860

Reputation: 190

3

Vim, 11, 10 bytes

qqvUW@qq@q

Explanation:

qq           #Start recording in register 'q'
  vU        #Make the character under the cursor uppercase
     W       #Move forward a WORD
      @q     #recursively call macro 'q'
        q    #stop recording
         @q  #Call the recursive macro

Do I get a gold-badge for outgolfing Dennis?

James

Posted 2015-05-10T23:23:16.860

Reputation: 54 537

3Yes, here's your gold badge – Downgoat – 2016-06-27T05:45:51.963

2

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

Benjamin Urquhart

Posted 2015-05-10T23:23:16.860

Reputation: 1 262

2

Bash, 61

a="${@//: / }"
a=(${a//: / })
a="${a[@]^}"
echo "${a//:/ }"

Note the colons are simply to make the program display OK here. In reality these can be some non-printable character, such as BEL.

Output

$ ./cap1st.sh "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
$ 

Bash, 12

Sadly this one doesn't preserve leading/mutliple/trailing spaces, but otherwise it works:

echo "${@^}"

Output

$ ./cap1st.sh 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
$ 

Digital Trauma

Posted 2015-05-10T23:23:16.860

Reputation: 64 644

5But that's half the challenge! – Sp3000 – 2015-05-11T02:47:56.240

1@Sp3000 there I fixed it (at as cost of 49 chars) – Digital Trauma – 2015-05-11T03:41:01.087

2

C#, 133 131

using C=System.Console;class P{static void Main(){var s=2>1;foreach(var c in C.ReadLine()){C.Write(s?char.ToUpper(c):c);s=c==32;}}}

Blorgbeard is out

Posted 2015-05-10T23:23:16.860

Reputation: 123

Do you need &&c!=32? I'm not too fluent in C#, but I would guess that converting a space to uppercase results in a space. – DLosc – 2015-05-11T04:01:37.533

Whoops, thanks - that was from before I made some other changes, I think. You're correct it's not needed. – Blorgbeard is out – 2015-05-11T04:25:26.697

try "using C=System.Console;" instead of using system – Ewan – 2015-05-11T11:38:43.233

2

Pip, 15 + 1 for -s = 16

{IaUC:a@0a}Ma^s

Explanation:

                  a is first cmdline arg (implicit)
            a^s   Split a on spaces
{         }M      Map this function to each element:
 Ia                 If the word is not empty,
   UC:a@0             uppercase its first character
         a          Return the word
                  Output the resulting list (implicit) joined on spaces (-s flag)

One interesting feature of Pip that this program draws on is the : assignment meta-operator. Most C-like languages have some set of compute-and-assign operators: e.g. x*=5 does the same thing as x=x*5. In Pip, however, you can tack : onto any operator and turn it into a compute-and-assign operator. This even goes for unary operators. So -:x computes -x and assigns it back to x, the same as x:-x would. In this case, UC: is used (together with Pip's mutable strings) to uppercase the first character of a word.

The program takes input from the command-line, requiring an invocation like this:

python3 pip.py -se "{IaUC:a@0a}Ma^s" "test teSt TEST  _test"

DLosc

Posted 2015-05-10T23:23:16.860

Reputation: 21 213

2

JavaScript (SpiderMonkey 31 (1.8)) 63 70

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

edc65

Posted 2015-05-10T23:23:16.860

Reputation: 31 086

Nice method! Here's -3 : [for(c of x=prompt(o=''))(o+=x?c.toUpperCase():c,x=c<'!')],alert(o) – nderscore – 2015-05-11T06:03:14.823

1I can't sleep... so it's -7 now : [for(c of prompt(o=x=''))o+=x=x<'!'?c.toUpperCase():c];alert(o) – nderscore – 2015-05-11T06:37:29.950

@nderscore wow your inexhaustible. I'm sorry I never find a way to give back – edc65 – 2015-05-11T06:46:04.063

I'm just happy to aid in the quest for the smallest possible JS solution :) – nderscore – 2015-05-11T06:48:05.830

Array comprehensions have been dropped from ES6 and ES7 altogether. Therefore, this is invalid JavaScript. – Chiru – 2015-08-04T08:38:07.327

@chiru it can be invalid, but, curiously, it works. Should we call it "javascript as implemented in current release of FireFox"? – edc65 – 2015-08-04T20:26:07.883

Well, it was an experimental SpiderMonkey feature, as it was planned for ES6 but later dropped, as no TC39 member wanted to champion it. It is not standards-compliant JavaScript and never was (and future releases of Firefox are likely drop its support).

– Chiru – 2015-08-04T23:15:26.153

@Chiru ok it is not standard-compliant. Who cares? It's code golf and it works. – edc65 – 2015-08-05T16:57:40.077

@edc65 I'm just saying, this isn't "ES6" (which is what it says right on the top of the answer). It should rather be tagged "JavaScript SpiderMonkey 31 (1.8)", so future users are aware of why there are syntax errors when they try to run this. – Chiru – 2015-08-05T17:07:08.200

1@Chiru agreed. And thanx for giving the exact version. – edc65 – 2015-08-05T17:09:43.413

2

R, 139 105 bytes

for(i in 1:length(p<-strsplit(readline(),"")[[1]])){if(i<2||p[i-1]==" ")p[i]=toupper(p[i])};cat(p,sep="")

Ungolfed + explanation:

# Assign p to be a vector of the input read from stdin, split into characters

for(i in 1:length(p <- strsplit(readline(), "")[[1]])) {

    # If we're at the first iteration or the previous character was a space

    if (i < 2 || p[i-1] == " ") {

        # Convert the current character to its uppercase equivalent

        p[i] <- toupper(p[i])
    }
}

# Join the vector elements into a single string and print it to stdout
cat(p, sep = "")

R with regex, 49 41 + 30 = 71 bytes

I'm really bummed; this actually has a better score using regular expressions with the penalty.

gsub("(^.| +.)","\\U\\1",readline(),pe=T)

This matches any single character at the beginning of the string or following any number of spaces and replaces it with an uppercase version of the capture. Note that applying \\U is legit and has no effect for non-letters. pe=T is interpreted as perl = TRUE since it takes advantage of R's partial matching of function parameters and the synonym for TRUE. For whatever reason, R doesn't use Perl-style regular expression by default.

Thanks to MickyT for helping save 8 bytes on the regex approach!

Alex A.

Posted 2015-05-10T23:23:16.860

Reputation: 23 761

With your regex the matching string could be (^.| +.). Uppercasing anything is OK. – MickyT – 2015-05-11T20:49:49.483

@MickyT: Good idea, thanks! Edited to use your suggestion. – Alex A. – 2015-05-11T20:54:19.097

2

C, 125

Not the shortest of solutions, but I really like to golf in C.

char b[99];main(c){while(scanf("%[A-Za-z_-]",b)==1)islower(*b)&&(*b&=223),printf("%s",b);~(c=getchar())&&putchar(c)&&main();}

ungolfed:

char b[99];
main(c)
{
  while(scanf("%[A-Za-z_-]", b) == 1) {
    if(islower(b[0])) {
      b[0] &= 0xDF;
    }
    printf("%s", b);
  }
  if((c = getchar()) != -1) {
      putchar(c);
      main();
  }
}

I don't know wheter using regex-like syntax in scanf is streching the rules, but it works quite nicely. (Well, technically it's not a full regex)

An other thing to consider is that this code only works for words shorter than 99 bytes. But I think this solution will work for most cases.

MarcDefiant

Posted 2015-05-10T23:23:16.860

Reputation: 996

Hint: &=223 --> -=32 – edc65 – 2015-05-11T08:19:27.593

2

Haskell: 127 characters

import Data.List
import Data.Char
i=isSpace
s a b=i a==i b
u (w:ws)=(toUpper w):ws
f w=concatMap u$groupBy s w
main=interact f

poida

Posted 2015-05-10T23:23:16.860

Reputation: 121

I got down to 69 bytes.

– Lynn – 2015-05-11T17:11:14.057

2

PHP, 82

echo join(' ',array_map(function($s){return ucfirst($s);},explode(' ',$argv[1])));

Usage :

$ php code.php "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"

kuldeep.kamboj

Posted 2015-05-10T23:23:16.860

Reputation: 625

2

Java, 201 178 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!)

TNT

Posted 2015-05-10T23:23:16.860

Reputation: 2 442

I did them one better :^) – Benjamin Urquhart – 2019-05-08T03:18:06.383

2

Python 2, 64 59 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:],

mbomb007

Posted 2015-05-10T23:23:16.860

Reputation: 21 944

@StevenRumbalski Fixed. – mbomb007 – 2015-05-11T20:41:34.583

I think you can do w and w[0].upper()+w[1:]. Not sure about the input format though. – Sp3000 – 2015-05-11T23:56:20.777

@StevenRumbalski Fixed – mbomb007 – 2015-05-12T16:44:58.263

2

Mathematica, 66 bytes

Print@StringReplace[InputString[],WordBoundary~~a_:>ToUpperCase@a]

I would use ToCamelCase, but it doesn't preserve spacing.

LegionMammal978

Posted 2015-05-10T23:23:16.860

Reputation: 15 731

2

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)

MickyT

Posted 2015-05-10T23:23:16.860

Reputation: 11 735

2

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

gcx11

Posted 2015-05-10T23:23:16.860

Reputation: 21

3This not preserves multiple whitespaces. – manatwork – 2015-05-12T08:03:56.210

2

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:]))

Tim

Posted 2015-05-10T23:23:16.860

Reputation: 2 789

2

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

James

Posted 2015-05-10T23:23:16.860

Reputation: 54 537

1

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.

Unrelated String

Posted 2015-05-10T23:23:16.860

Reputation: 5 300

1

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)

Kevin Cruijssen

Posted 2015-05-10T23:23:16.860

Reputation: 67 575

1

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

manatwork

Posted 2015-05-10T23:23:16.860

Reputation: 17 865

1

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?"

dieter

Posted 2015-05-10T23:23:16.860

Reputation: 2 010

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 – 2015-05-11T09:56:32.117

thanks -- Actually It seems (at last with GNU sed, that it dors not need the -r option) – dieter – 2015-05-11T10:06:04.160

Grr! I felt something is not optimal there since I first read this. s/^.| +./\U&/g – manatwork – 2015-05-11T17:19:56.850

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 – 2016-09-03T10:49:16.377

Almost there, the usage doesn't reflect the code. It should be sed -r 's/(^| +)(.)/\1\u\2/g' <<<. – seshoumara – 2016-09-03T14:39:01.717

thanks -- Actually It seems (at last with GNU sed), that it does not need the -r option – dieter – 2016-09-03T14:47:22.173

3So 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 – 2016-09-06T19:08:25.200

1

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.

Ismael Miguel

Posted 2015-05-10T23:23:16.860

Reputation: 6 797

1Your regular expression has a minor glitch. Should be @( |^)([a-z])@ as currently not processes the first word. – manatwork – 2015-05-11T16:08:42.127

@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 – 2015-05-11T16:18:15.263

Why not ucwords? – Jörg Hülsermann – 2017-05-17T18:30:52.660

@JörgHülsermann Because of https://codegolf.stackexchange.com/a/49980/14732 and because of rule #1.

– Ismael Miguel – 2017-05-17T18:49:59.193

1

C#, 143 138123 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!

Transmission

Posted 2015-05-10T23:23:16.860

Reputation: 71

Instead of using ' ' you can use the ascii integer equivalent - 32 - which will save you two bytes :) – ldam – 2015-05-14T13:07:35.977

1

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.

MegaTom

Posted 2015-05-10T23:23:16.860

Reputation: 3 787

1

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

draegtun

Posted 2015-05-10T23:23:16.860

Reputation: 1 592

1

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.

Ruben Dijkstra

Posted 2015-05-10T23:23:16.860

Reputation: 17

1

Groovy - 69

t=args[0];t.eachWithIndex{c,i->print!i|t[i-1]==' '?c.toUpperCase():c}

dbramwell

Posted 2015-05-10T23:23:16.860

Reputation: 201

1

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"

WooiKent Lee

Posted 2015-05-10T23:23:16.860

Reputation: 413

1

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.

Dennis

Posted 2015-05-10T23:23:16.860

Reputation: 196 637

It's non-competing anyways, so you could use K instead of j⁶. – Erik the Outgolfer – 2016-10-27T09:23:14.503

1

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.

Erik the Outgolfer

Posted 2015-05-10T23:23:16.860

Reputation: 38 134

0

Python 2, 51 bytes

lambda s:' '.join(map(str.capitalize,s.split(' ')))

Try it online!

ovs

Posted 2015-05-10T23:23:16.860

Reputation: 21 408

0

JavaScript, (ES6 RegEx Replacer) 66 bytes

alert(prompt().replace(/(^[A-Z])|(\s[A-Z])/gi,m=>m.toUpperCase()))

zfrisch

Posted 2015-05-10T23:23:16.860

Reputation: 101

0

Perl 6, 35 bytes

say slurp.split(" ")>>.tc.join(" ")

Try it online!

bb94

Posted 2015-05-10T23:23:16.860

Reputation: 1 831

1

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 – 2019-05-06T21:58:15.550

0

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.

brhfl

Posted 2015-05-10T23:23:16.860

Reputation: 1 291

0

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) + " ");
        }
    }
}

Vartan

Posted 2015-05-10T23:23:16.860

Reputation: 231

You don't need braces for the For(), and I think substring(0,1) can be charAt(0). – lirtosiast – 2015-08-18T15:37:56.183

The public modifier before the class definition can be removed. – Yytsi – 2016-06-20T14:10:53.183