每个输入单词的首字母大写


34

这是一个相对较快的方法,但是我敢肯定您会喜欢的。

Codegolf一个程序,它将以句子的形式接受输入,然后为输出提供每个单词大写的首字母。

规则:

  1. 提交内容可能不是函数形式。所以不行:

    function x(y){z=some_kind_of_magic(y);return z;} 作为您的最终答案...您的代码必须表明它接受输入并提供输出。

  2. 该代码必须保留输入中包含的任何其他大写字母。所以

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

    将呈现为

    ECommerce And EBusiness Are Cool, Don't You Agree, Richard III?
    
  3. 你们中有些人可能会想:“容易,我只使用正则表达式!” 因此在您选择的高尔夫语言中使用本地正则表达式将导致30个字符的罚款,这将应用于您的最终代码计数。邪恶的笑

  4. 在这种情况下,“单词”是由空格分隔的任何内容。因此palate cleanser是两个字,而pigeon-toed被视为一个字。if_you_love_her_then_you_should_put_a_ring_on_it被认为是一个字。如果单词以非字母字符开头,则会保留该单词,因此_this在渲染后仍为_this。(对Martin Buttner指出此测试用例表示敬意)。

    • 4b。不能保证输入短语中的单词将由单个空格分隔。
  5. 测试用例,(请用于测试您的代码):

    输入:

    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
    
  6. 这是代码高尔夫球,最短的代码获胜...

祝好运...


1
行尾的空格呢?我们必须保存它们吗?如果可以满足我们的需求,我们可以添加一个吗?
丹尼斯

2
丹尼斯,请保留输入中的空格...
WallyWest

3
!= TitleCase该死!C#再次失去!
伊万2015年

1
@Tim Pigeon-toed之前的双倍空格是正确的。他说要保持间隔。
mbomb007

2
单词之间是什么分开?是否有空格(制表符,换行符等)还是仅空格?
史蒂芬·鲁姆巴尔斯基

Answers:


21

CJam,15 13字节

Lq{_eu?_S-}/;

CJam解释器中在线尝试。

伪码

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)

所有修改的字符C都保留在堆栈上,因此在退出时打印。


3
该死的,这很聪明。D:
马丁·恩德

我必须同意,用一种代码高尔夫语言将某人打败4个字符本身就是一项壮举……做得很好。
WallyWest

12
@WallyWest:高尔夫语言可以给人一种他们自己喜欢高尔夫的印象,但我向您保证他们不会。TMTOWTDI适用于所有语言,尤其是对于那些内置很多语言的语言。有时候你赢了,有时输了,有时觉得自己被卡车撞到了
丹尼斯,2015年

13

CSS 2.1、49

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

说明

可运行的代码段

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

注意CSS 2.1指定了所需的行为:capitalize将每个单词的第一个字符大写。但是,CSS3大写每个单词的第一个印刷字母单位。因此,以上代码段在旧版IE(不遵循CSS 2.1)上均无法正常运行;也不遵循CSS3的新兼容浏览器。


哦,这很聪明!
IQAndreas 2015年

1
_those对于CSS3浏览器上的问题太糟糕了,但是由于解决问题的独特方式,我仍在投票。)
IQAndreas 2015年

@Oriol,“哦,这很聪明!” 确实!对不起IQAndreas,我不得不在这里借用您的评论...这是解决问题的一种巧妙方法...我将不得不利用这种方法...
WallyWest 2015年

10

Javascript(ES6),77个字节

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

已评论

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
)

如果单词被多个空格分隔会怎样?[4b]
Caek 2015年

3
@Caek由处理x&&。空字符串是falsey,因此&&短路并返回左操作数,即空字符串。保留空间。
nderscore 2015年

太好了,谢谢您的解释。可能会帮助我弄清楚如何立即开始工作。
Caek

这将大写非Ascii字符,因此å将变成Å!
狮子座

9

Perl,13个字节

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

9个字节加4个字节040p(假设我已经正确解释了特殊调用规则)。

-040将输入记录分隔符$/设置为单个空格,以便保留空格;该\u转义序列转换下一个字符标题情况。


很棒的工作,使用命令行值得一提!
WallyWest

7

CJam,17个 15字节

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

在这里测试。

规范的直接实现。利用新{}&功能避免连续空格出现错误。

Dennis保存了两个字节。


好东西!CJam主要是只是一种高尔夫语言,还是有一些实际的商业应用?
WallyWest

6
@WallyWest不,这只是一种高尔夫语言。它肯定没有商业应用程序,但是我个人偶尔将其用于快速丢弃的脚本(因为它具有很多内置函数,并且如果您知道自己在做什么,那么输入较少的字符比输入要快更多字符;)。
马丁·恩德

您可以通过在每个单词后添加一个空格来节省一些字节。根据OP对我问题的回答,这可能使您达到14或12个字节。
丹尼斯

@Dennis哦,对了,我一直在玩,但是没有考虑在添加第一个字符之前简单地添加它。明天我会改变的,谢谢!
马丁·恩德

@Dennis谢谢,我更改了它,但是我不确定您的意思是14字节版本。如果您正在谈论省略第二个+,那么如果输入包含尾随空格,则会中断。
马丁·恩德

7

C,64 63字节

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

修复:一些编译器(例如Clang)不喜欢使用int参数代替argv,因此我将其移至全局变量。字节数保持不变。多亏了吱吱作响的ossifrage的注意。 减少到63个字节,感谢Dennis。

取消高尔夫:

int a;

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

非常简单:如果a为假,则字符转换为大写。在读取空格后进行设置:仅当c ==''时c-''为false。toupper()会忽略所有不是小写字母的内容,因此可以使用符号和多个空格。-1设置了所有位,因此当getchar()返回-1时,NOT运算符将其设置为零,然后循环停止。将a声明为全局变量,因此将其初始化为零(假)。这样可以确保第一个单词大写。


1
while(~(c=getchar())- 我喜欢。Clang实际上不会编译它,但是您可以通过c;main(a){...}
sosamage ossifrage

1
如果交换三元运算符的ac和的声明,则可以替换==-以节省一个字节。
丹尼斯

你是对的,当然。
安德里亚·比昂多

真好!+1使用时while(!(c = getchar())),程序将运行相同,对吗?
Spikatrix

1
@酷家伙:不,按位~与逻辑!不相同。在C中,任何不为零的东西都被认为是正确的,因此您的条件就像是while((c = getchar()) == 0)哪种当然不起作用。按位NOT运算符逐~位取反该值。要打破循环,~c必须为零:这意味着所有位都必须为1,以便在取反时变为全零。该值(对于32位int)为0xFFFFFFFF,如果带符号,则为-1(EOF)。
安德里亚·比昂多

7

Python 3,59 56字节

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

感谢@Reticality提供了3个字节。


3
怎么print(end=f*c.upper()or c)样 这样可以节省4个字节

@Reticality哦,我不知道您可以只使用关键字arg来打印空白。谢谢!
Sp3000

7

Perl的版本<5.18,30 27 26 25

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

24字符+1-n

\u使字符串中的下一个字符变为大写。@ThisSuitIsBlackNot指出可以节省1个字节。在使用函数之前ucfirst

perldocs中

作为另一种特殊情况,当省略PATTERN或由单个空格字符组成的文字字符串(例如''或“ \ x20”,但不包括/ /)时,split模仿命令行工具awk的默认行为。在这种情况下,EXPR中的任何前导空格都在拆分之前被删除,而PATTERN则被视为/ \ s + /;特别是,这意味着将任何连续的空格(不仅仅是一个空格字符)用作分隔符。但是,可以通过指定模式/ /而不是字符串“”来避免这种特殊处理,从而仅允许将单个空格字符用作分隔符。在早期的Perls中,这种特殊情况在Perl 5.18中仅限于使用普通的“”作为sp​​lit的模式参数。

由于$"求值空间,因此将保留空间。由于我们既要设置$,为空格字符,又要为拆分输入空格,因此@nutki指出我们都可以将其作为拆分的输入。这比我们之前的设置节省了3个字节,该设置是首先设置的$,,然后输入$"拆分。

如@ alexander-brett所指出的,使用,for映射而不是{}节省额外的字节。

运行:

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$,=$"'

1
使用...map"\u$_",split...
亚历山大·布雷特

@alexander-brett thanks! I updated the answer.
hmatt1

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.

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

This is my first answer in PCG, not sure if this is acceptable.
Atul Kumbhar

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

Thanks @nderscore for the hint, I have edited my answer using the tips.
Atul Kumbhar

Looking better! I also added the byte count into your post for you.
nderscore

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

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(); }

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

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.


2
You could save 2 bytes by porting to Python 3. (-4 raw_input => input, +2 print => print())
Steven Rumbalski

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

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


Personally I consider only fgets(STDIN) to read input. But we have no consensus on $_GET as far as I know.
manatwork

Yup, that works :D
Octfx

You don't need the tricks to shut up the warnings. Thei're warnings! Nobody cares about them.
Ismael Miguel

Well, didn't thought of that. Guess I'll have to stick to substr
Octfx

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

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.


Nice! Can you please explain it for me?
poida

I wrote an explanation.
Lynn

Some more scanl examples: one, two.
Lynn

@Mauris kudos for using such a great algorithmm like this... :)
WallyWest

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.


1
The 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

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.


1
Chaining f and . is pretty ingenious. Another 14 bytes variant: qS/Sf.{\eu}S.-
Dennis

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


1
Welcome to PPCG! Surely, you don't need those spaces after commas?
Martin Ender

Wow, I'm so new to this I didnt even know spaces counted. 62 bytes!

2
I 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

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


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

1
Welcome to PPCG! The public modifier isn't necessary so you can save 7 more.
TNT

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

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

@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

That didn't crossed my mind. There must be a bitwise trick to check if it is a letter or not.
Ismael Miguel

1
One thing you can do is $l=str_split(fgets(STDIN)), which reduces the code by 2 bytes!
Ismael Miguel

1
Now I'm going mad. Man, how long I starred to that initialization and missed it. Thank you, @IsmaelMiguel.
manatwork

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.


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


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
$ 

5
But that's half the challenge!
Sp3000

1
@Sp3000 there I fixed it (at as cost of 49 chars)
Digital Trauma

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"

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.


Hint: &=223 --> -=32
edc65

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

I got down to 69 bytes.
Lynn

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"

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;}}}

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

Whoops, thanks - that was from before I made some other changes, I think. You're correct it's not needed.
Blorgbeard

try "using C=System.Console;" instead of using system
Ewan

2

Mathematica, 66 bytes

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

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


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!


With your regex the matching string could be (^.| +.). Uppercasing anything is OK.
MickyT

@MickyT: Good idea, thanks! Edited to use your suggestion.
Alex A.
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.