34
\$\begingroup\$

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

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

56 Answers 56

2
\$\begingroup\$

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!)

\$\endgroup\$
2
\$\begingroup\$

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:],
\$\endgroup\$
  • \$\begingroup\$ @StevenRumbalski Fixed. \$\endgroup\$ – mbomb007 May 11 '15 at 20:41
  • \$\begingroup\$ I think you can do w and w[0].upper()+w[1:]. Not sure about the input format though. \$\endgroup\$ – Sp3000 May 11 '15 at 23:56
  • \$\begingroup\$ @StevenRumbalski Fixed \$\endgroup\$ – mbomb007 May 12 '15 at 16:44
2
\$\begingroup\$

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

\$\endgroup\$
  • 3
    \$\begingroup\$ This not preserves multiple whitespaces. \$\endgroup\$ – manatwork May 12 '15 at 8:03
2
\$\begingroup\$

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:]))
\$\endgroup\$
2
\$\begingroup\$

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)

\$\endgroup\$
2
\$\begingroup\$

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)

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

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
\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Your regular expression has a minor glitch. Should be @( |^)([a-z])@ as currently not processes the first word. \$\endgroup\$ – manatwork May 11 '15 at 16:08
  • \$\begingroup\$ @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. \$\endgroup\$ – Ismael Miguel May 11 '15 at 16:18
  • \$\begingroup\$ Why not ucwords? \$\endgroup\$ – Jörg Hülsermann May 17 '17 at 18:30
  • \$\begingroup\$ @JörgHülsermann Because of codegolf.stackexchange.com/a/49980/14732 and because of rule #1. \$\endgroup\$ – Ismael Miguel May 17 '17 at 18:49
1
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ Instead of using ' ' you can use the ascii integer equivalent - 32 - which will save you two bytes :) \$\endgroup\$ – ldam May 14 '15 at 13:07
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Groovy - 69

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

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
\$\endgroup\$
1
\$\begingroup\$

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"
\$\endgroup\$
1
\$\begingroup\$

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.
\$\endgroup\$
  • \$\begingroup\$ It's non-competing anyways, so you could use K instead of j⁶. \$\endgroup\$ – Erik the Outgolfer Oct 27 '16 at 9:23
1
\$\begingroup\$

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?"
\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – manatwork May 11 '15 at 9:56
  • \$\begingroup\$ thanks -- Actually It seems (at last with GNU sed, that it dors not need the -r option) \$\endgroup\$ – dieter May 11 '15 at 10:06
  • \$\begingroup\$ Grr! I felt something is not optimal there since I first read this. s/^.| +./\U&/g \$\endgroup\$ – manatwork May 11 '15 at 17:19
  • \$\begingroup\$ 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. \$\endgroup\$ – seshoumara Sep 3 '16 at 10:49
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ – seshoumara Sep 6 '16 at 19:08
1
\$\begingroup\$

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.
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$
0
\$\begingroup\$

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) + " ");
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ You don't need braces for the For(), and I think substring(0,1) can be charAt(0). \$\endgroup\$ – lirtosiast Aug 18 '15 at 15:37
  • \$\begingroup\$ The public modifier before the class definition can be removed. \$\endgroup\$ – Yytsi Jun 20 '16 at 14:10
0
\$\begingroup\$

Python 2, 51 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

JavaScript, (ES6 RegEx Replacer) 66 bytes

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

\$\endgroup\$
0
\$\begingroup\$

Perl 6, 35 bytes

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

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ You can rempve the join and just stringify it instead. slurp can also be get since there won't be newlines. 24 bytes \$\endgroup\$ – Jo King May 6 at 21:58
0
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.