Ini relatif cepat, tapi saya yakin Anda akan menyukainya.
Codegolf program yang akan mengambil input dalam bentuk kalimat dan kemudian memberikan output dengan huruf pertama dikapitalisasi dalam setiap kata.
Aturan:
Pengajuan mungkin tidak dalam bentuk fungsi. Jadi tidak:
function x(y){z=some_kind_of_magic(y);return z;}
sebagai jawaban akhir Anda ... Kode Anda harus menunjukkan bahwa ia mengambil input, dan memberikan output.Kode harus mempertahankan huruf kapital lain yang dimiliki input. Begitu
eCommerce and eBusiness are cool, don't you agree, Richard III?
akan diterjemahkan sebagai
ECommerce And EBusiness Are Cool, Don't You Agree, Richard III?
Beberapa dari Anda mungkin berpikir, "Mudah, saya hanya akan menggunakan regex!" dan dengan menggunakan regex asli dalam bahasa golf pilihan Anda akan dikenakan penalti 30 karakter yang akan diterapkan pada jumlah kode akhir Anda. Tertawa jahat
"Kata" dalam hal ini adalah apa pun yang dipisahkan oleh spasi. Karena itu
palate cleanser
ada dua kata, sedangkanpigeon-toed
dianggap satu kata.if_you_love_her_then_you_should_put_a_ring_on_it
dianggap satu kata. Jika sebuah kata dimulai dengan karakter non-abjad, kata tersebut dipertahankan, jadi_this
setelah rendering tetap menjadi_this
. (Kudos to Martin Buttner untuk menunjukkan test case ini).- 4b. Tidak ada jaminan bahwa kata-kata dalam frasa input akan dipisahkan oleh satu spasi.
Test Case, (silakan gunakan untuk menguji kode Anda):
Memasukkan:
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
Keluaran:
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
Ini adalah kode golf, kode terpendek menang ...
Semoga berhasil...
sumber
Jawaban:
CJam,
1513 byteTry it online in the CJam interpreter.
Pseudocode
All modified characters C are left on the stack and, therefore, printed when exiting.
sumber
CSS 2.1, 49
Explanation:
attr
function takes the input from at
(text) HTML attribute.text-transform
tocapitalize
.content
property on an::after
pseudo-element.Runnable snippet:
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.sumber
_those
problem on CSS3 browsers, but I'm still upvoting because of the unique way of solving the problem.)Javascript (ES6), 77 bytes
Commented
sumber
x&&
. An empty string is falsey so the&&
short-circuits and returns the left operand, the empty string. Spaces are preserved.Perl, 13 bytes
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.sumber
CJam,
1715 bytesTest it here.
Fairly straightforward implementation of the spec. Make use of the new
{}&
to avoid errors for consecutive spaces.Two bytes saved by Dennis.
sumber
+
, then that breaks if the input contains trailing spaces.C,
6463 bytesFix: 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:
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.
sumber
while(~(c=getchar())
— I like that. Clang won't actually compile this, but you can get the same character count withc;main(a){...}
a
andc
and the order of the ternary operator, you can replace==
with-
to save one byte.while(!(c = getchar()))
, right?~
and the logical!
are not the same. In C anything that is not zero is considered true, so your condition would be likewhile((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) is0xFFFFFFFF
, which, if signed, is-1
(EOF).Python 3,
5956 bytesThanks to @Reticality for 3 bytes.
sumber
print(end=f*c.upper()or c)
? That would save 4 bytesPerl Version < 5.18,
3027262524
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 functionucfirst
.From the perldocs,
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:
sumber
...map"\u$_",split...
><> (Fish), 39 bytes
Method:
a-z
then print it out. (left-to-right code for this part isi::'backquote')$'{'(*' '*+
)sumber
JAVA, 273 bytes
EDIT
sumber
public
in front of theclass
.. And if you mean he can remove thepublic
in front of thestatic void main(...
, then you are wrong, unless he also changes theclass
tointerface
and uses Java 8+.JavaScript (regex solution) - 104 bytes
Someone has to bite the bullet and post the RegEx solution! 74 characters, plus the +30 character penalty:
Or if you want to read and understand the code in its non-compacted fashion:
sumber
Python 2, 73 bytes
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.sumber
raw_input
=>input
, +2print
=>print()
)PHP 64
7677838489bytesDoes
$_GET
count as input in PHP?If so, here is my first CG attempt
Thanks manatwork :)
One could just use the
ucwords
function, which would result in 21 bytes:thanks Harry Mustoe-Playfair :)
sumber
fgets(STDIN)
to read input. But we have no consensus on$_GET
as far as I know.$k=>
. Put it back:foreach(split(' ',$_GET[@s])as$k=>$v)echo$k?' ':'',ucfirst($v);
Haskell, 69
Explanation:
scanl
takes a function(a -> b -> a)
and an initial valuea
, then iterates over a list of[b]
s to make a list of[a]
s: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). Forscanl
, this means: return the value from the input list, but capitalize it if the previous result was a space. Soscanl (!) ' ' "ab cd"
becomes:We need the initial value
' '
to capitalize the first letter, but then we chop it off withtail
to get our final result.sumber
scanl
examples: one, two.Pyth, 20 bytes
These multiple spaces really sucks. Otherwise there would have been a really easy 12 bytes solution.
Try it online: Pyth Compiler/Executor
Explanation
edit: 16 chars is possible with @Dennis algorithm.
sumber
CJam, 14 bytes
It's not the shortest, but...
Another answer using similar ideas:
.x
only changes the first item if one of the parameters has only one item.sumber
f
and.
is pretty ingenious. Another 14 bytes variant:qS/Sf.{\eu}S.-
Lua,
646261 bytesLua is a horrendous language to golf in, so I'm pretty proud of myself for this one.
[Try it here]1 Outdated, will update tommorowsumber
abc_def
will giveAbc_Def
. However only letters after spaces should be turning into upper case. The good news is, fixing it saves a byte. ;)JAVA, 204
211226bytesMy first entry on CG, I hope it's fine:
Saved 7 bytes thanks to @TNT
sumber
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);}}
public
modifier isn't necessary so you can save 7 more.PHP:
7674 charactersSample run:
sumber
ucfirst($c)
, use$c^' '
. (Tip: if youbitwise-xor
a letter with a space, it will be converted from uppercase to lowercase, and the oposite applies too)$l=str_split(fgets(STDIN))
, which reduces the code by 2 bytes!C, 74 bytes
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 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.sumber
C# Linq - 187
This is nowhere close to winning but I just love Linq too much.
sumber
Vim,
11, 10 bytesExplanation:
Do I get a gold-badge for outgolfing Dennis?
sumber
Bash, 61
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
Bash, 12
Sadly this one doesn't preserve leading/mutliple/trailing spaces, but otherwise it works:
Output
sumber
Pip, 15 + 1 for
-s
= 16Explanation:
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 asx=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 tox
, the same asx:-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:
sumber
C, 125
Not the shortest of solutions, but I really like to golf in C.
ungolfed:
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.
sumber
Haskell: 127 characters
sumber
PHP, 82
Usage :
sumber
C#,
133131sumber
&&c!=32
? I'm not too fluent in C#, but I would guess that converting a space to uppercase results in a space.Mathematica, 66 bytes
I would use
ToCamelCase
, but it doesn't preserve spacing.sumber
R,
139105 bytesUngolfed + explanation:
R with regex,
4941 + 30 = 71 bytesI'm really bummed; this actually has a better score using regular expressions with the penalty.
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 asperl = TRUE
since it takes advantage of R's partial matching of function parameters and the synonym forTRUE
. 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!
sumber
(^.| +.)
. Uppercasing anything is OK.