Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Given a string, capitalize it. By capitalization I mean conTeNT-lENgth changes to Content-Length. In the example I showed the string with 2 words with - as the word boundary. However I expect you to write the code for the string containing any number of words separated by a single character as the boundary. This boundary may change across the string.

Conditions

  1. using regular expressions is not allowed.
  2. there could be any number of words in a sentence(string).
  3. each word will consist of English letters[a-zA-Z] of any case.
  4. different words in the sentence will be separated by a single character. This character will only be any one of -, ., <space-character>, /, &, #. You can safely assume that sentence will not contain any other character except the mentioned ones.
  5. word boundaries should be preserved in the output.
  6. shortest code wins.

For example your program should output Begin/With.Type&Content for BeGin/wITH.tyPE&conTeNt.

Some test cases:
 "aGeNT ACcEpT/LEngTh-tYPe USeR raNgE.TyPe" 
 "type&AgeNt/CC/COnteNt lEnGth#acCePT/AgeNt.RAnGe-Cc/contEnt/cODe" 
 "cc/rEspoNCe.lEngtH#tYpE-witH&UsEr/bEgIN&uSer.AGEnT&begIn/aCCEPt/Cc" 
 "lENgTH#USeR.tYpE/BeGiN&LENGth tYpe/ACCEpt#rANge/codE&AnD-ACCepT/ConTenT" 
 "contENT/ACcEpT" 
 "BeGin/wITH.tyPE&conTeNt"
 "Code.cc#User.lenGTh-USer-AND&tyPE TypE&leNgtH.tYPe usER.UseR&with" 
 "RaNgE&COnTeNT WITh CoNTENT-TypE tyPe"
 "BEgin COdE#uSeR#aGeNt.USeR"
 "TypE LENGth"
share|improve this question
1  
What you call capitalization is actually a transformation to camel-case. –  Pierre Arlaud Dec 17 '13 at 14:03
4  
@ArlaudPierre No, what he's given as "test cases" are more like camel case. What's being called capitalization is closer to Title Case. –  Iszi Dec 17 '13 at 14:42
    
Can you please provide the expected output for the test cases? It seems some built-in functions may assume that all-caps words (like /CC/ in line 2, or -AND& in line 7) should be left alone. Is this ok, for this challenge? –  Iszi Dec 17 '13 at 14:44
    
Does the input always begin with a word or it may start with a separator? –  lebatsnok Jan 2 at 15:04

17 Answers 17

up vote 7 down vote accepted

GolfScript, 36 27 19 characters

0\{95&+.47>32*\}%\;

A quite basic GolfScript approach which works for all input according to the specification. The examples can be tested online.

share|improve this answer
    
Cool. Was curious whether my solution is at least twice as a professional one. :) But I am sure you will shorten this several times before the day ends. –  manatwork Dec 17 '13 at 12:15
    
@manatwork Now we have a factor of two ;-) Still unhappy with all the swaps. –  Howard Dec 17 '13 at 13:50
    
I knew you will not disappoint me. –  manatwork Dec 17 '13 at 13:52

Python 3,22

print(input().title())

This code will take a string as input from stdin and gives a capitalized output to stdout.

for example:

input:

BEGIN/wITH.tyPe&cOnTENt

ouput:

Begin/With.Type&Content

The following code is for multi-line inputs (if necessary)

Python 3, 46

import sys
for i in sys.stdin:print(i.title())
share|improve this answer
    
while 1:print(input.title()) is a shorter equivalent for the last piece of code. –  Ramchandra Apte Dec 17 '13 at 14:44
1  
@RamchandraApte I'm not sure is it allowed or not. Your code will die with an EOFError as soon as its hits the EOF –  Wasi Dec 17 '13 at 15:08
1  
I think the general consensus for golfs is that as long as the output is correct, errors don't matter –  Volatility Dec 17 '13 at 23:26
    
Dang; as soon as I saw this question, I thought of this, but you beat me to it. +1 –  Quincunx Dec 18 '13 at 6:38
    
+1 I like this better than the golfscript one because it doesn't look like an obscenity. –  Tim Seguine Jan 1 at 22:58

Mathematica 62

Data

tests={"aGeNT ACcEpT/LEngTh-tYPe USeR raNgE.TyPe","type&AgeNt/CC/COnteNt lEnGth#acCePT/AgeNt.RAnGe-Cc/contEnt/cODe","cc/rEspoNCe.lEngtH#tYpEwitH&UsEr/bEgIN&uSer.AGEnT&begIn/aCCEPt/Cc","lENgTH#USeR.tYpE/BeGiN&LENGth tYpe/ACCEpt#rANge/codE&AnD-ACCepT/ConTenT","contENT/ACcEpT","BeGin/wITH.tyPE&conTeNt","Code.cc#User.lenGTh-USer-AND&tyPE TypE&leNgtH.tYPe usER.UseR&with","RaNgE&COnTeNT WITh CoNTENT-TypE tyPe","BEgin COdE#uSeR#aGeNt.USeR","TypE LENGth"}

Code

StringReplace[ToLowerCase@#,WordBoundary~~x_:>ToUpperCase@x]&

Usage

f["aGeNT ACcEpT/LEngTh-tYPe USeR raNgE.TyPe"]

"Agent Accept/Length-Type User Range.Type"

f /@ tests

{"Agent Accept/Length-Type User Range.Type",
"Type&Agent/Cc/Content Length#Accept/Agent.Range-Cc/Content/Code", "Cc/Responce.Length#Type-With&User/Begin&User.Agent&Begin/Accept/Cc", "Length#User.Type/Begin&Length Type/Accept#Range/Code&And-Accept/Content", "Content/Accept",
"Begin/With.Type&Content",
"Code.Cc#User.Length-User-And&Type Type&Length.Type User.User&With",
"Range&Content With Content-Type Type",
"Begin Code#User#Agent.User",
"Type Length"}

share|improve this answer

JavaScript (94)

prompt().split(l='').map(function(a){return l='A'>l?a.toUpperCase():a.toLowerCase()}).join('')
share|improve this answer

PHP : 78 73 65 64 characters

$b=ucfirst;foreach(str_split($s)as$c)echo$b($c),!$b[0]=$c<A?u:l;

Input is passed in $s. It operates on the string as an array of characters.

It is a simple 2 state machine. It relies on lexical ordering of strings, and that the parser automatically assumes you meant to type a string in some cases.

The state is being stored in $b and is being represented as the name of the function that needs to be called on the next character. ucfirst and lcfirst are shorter to type and have identical behaviour to strtolower/strtoupper on single character strings. Also, since they only differ by one letter, we can use them efficiently to store the state. The original version needed to store the state explicitly in a boolean.

Since echo doesn't print anything for boolean false, I used a comma and the ! operator to "hide" the assignment(which in this case is truthy) in the echo statement. This allowed me to save a character by removing the {}.

share|improve this answer
    
Please use code block markup instead of inline code, so scripts like Code Golf UserScript Enhancement Pack can insert the size below the code. By the way, in your code all 3 space characters can be removed. –  manatwork Dec 29 '13 at 14:32
    
@manatwork thanks –  Tim Seguine Dec 29 '13 at 14:34
    
Instead of $b=ord($c)>64; try $b=$c>"@";. Or even $b=$c>=A; – AFAIR that throws a warning, but good coding practices are not a virtue here. –  manatwork Dec 29 '13 at 17:02
    
@manatwork thanks, didn't think of that. I am already throwing a warning for using an unset variable anyway. –  Tim Seguine Dec 29 '13 at 17:04
    
Hmm… What about not using $b just as a flag, but storing the actual function name in it? $b=ucfirst;foreach(str_split($s)as$c){echo$b($c);$b[0]=$c>=A?l:u;}. –  manatwork Dec 29 '13 at 17:08

C, 83

n;main(c){c=getchar();putchar(c>96?n?c:(n=c-32):c&64?n?c+32:(n=c):(n=0,c));main();}

Takes lines on stdin, translates them to stdout. (Prefers SIGINT to EOF.)

share|improve this answer

Powershell: 37 - 43

Depending on how you want to take the input...

Prompt the user for input: 43

(Culture).TextInfo.ToTitleCase((read-host))

Take input from pipeline: 38

(Culture).TextInfo.ToTitleCase($input)

Provide input as an argument when running the script: 37

(Culture).TextInfo.ToTitleCase($args)

NOTE: The above scripts will ignore all-caps words, leaving them as-is. If this needs to be accounted for, the input should be forced to lower-case before the Title Case conversion. This adds 10 characters to the first method, and 12 to the other two.

(Culture).TextInfo.ToTitleCase((read-host).ToLower())
(Culture).TextInfo.ToTitleCase("$input".ToLower())
(Culture).TextInfo.ToTitleCase("$args".ToLower())
share|improve this answer
    
Does not work according to the specification. Try foo:bar. –  Mormegil Dec 17 '13 at 15:33
    
@Mormegil Which one? The read-host version, at least, works fine for me. I tested it against all the test cases in the question and they all returned as expected except for the special cases I posted in comment to the question. –  Iszi Dec 17 '13 at 15:35
    
: (colon) is not listed as a word separator in rule #4, therefore, AFAICS, foo:bar should result in Foo:bar, not Foo:Bar. But that is just my (quite strict) reading of the specification. –  Mormegil Dec 17 '13 at 15:38
    
@Mormegil Ah, but an equally strict interpretation could also be that the rule does not provide an exclusive list. That is, it says the separator "could be any one of..." as opposed to "can only be any one of...". –  Iszi Dec 17 '13 at 15:40
2  
@Mormegil Well, this is neat. Looks like the spec was tweaked to resolve that ambiguity, while at the same time not invalidating this answer. –  Iszi Dec 17 '13 at 16:19

Befunge 98 - 24 45

~\j:'``!3*j' -;:'``b*j:'/`!3*j' +#;:,'/`!jc#@

Writing this hurt my brain.

This takes input through ~ and if the previous character was one of the separators (or if there was no previous character), it executes

:'``!3*j' -;

This snippet takes the character, and if its ascii value is greater than or equal to a, it subtracts 32 from it, thus changing it to upper case. If it is less than a, 3*j skips the adjustment. Afterwards, it skips the next part. This part handles changing from upper case to lower case (I'm sure it can be merged with the next part; I'm just not sure how):

:'``b*j:'/`!3*j' +#;

The character is printed (,), then this checks if the character is one of the boundaries:

'/`!

It basically compares the character to the ascii value of /. If the character is not a boundary, the code pushes 12 so that it will skip the capitalization adjustment the next time around. # skips over the end program: @, and if the end of the input is reached, ~ sends the code execution back to the @, ending the program.

share|improve this answer

Ruby: 60 51 50 47 characters

$_.downcase.chars{|c|$><<$/=$/<?0?c.upcase: c}

Sample run:

bash-4.1$ for line in "${test[@]}"; do printf '%-75s | %s\n' "$line" "$( ruby -ne '$_.downcase.chars{|c|$><<$/=$/<?0?c.upcase: c}' <<< "$line" )"; done
aGeNT ACcEpT/LEngTh-tYPe USeR raNgE.TyPe                                    | Agent Accept/Length-Type User Range.Type
type&AgeNt/CC/COnteNt lEnGth#acCePT/AgeNt.RAnGe-Cc/contEnt/cODe             | Type&Agent/Cc/Content Length#Accept/Agent.Range-Cc/Content/Code
cc/rEspoNCe.lEngtH#tYpE-witH&UsEr/bEgIN&uSer.AGEnT&begIn/aCCEPt/Cc          | Cc/Responce.Length#Type-With&User/Begin&User.Agent&Begin/Accept/Cc
lENgTH#USeR.tYpE/BeGiN&LENGth tYpe/ACCEpt#rANge/codE&AnD-ACCepT/ConTenT     | Length#User.Type/Begin&Length Type/Accept#Range/Code&And-Accept/Content
contENT/ACcEpT                                                              | Content/Accept
BeGin/wITH.tyPE&conTeNt                                                     | Begin/With.Type&Content
Code.cc#User.lenGTh-USer-AND&tyPE TypE&leNgtH.tYPe usER.UseR&with           | Code.Cc#User.Length-User-And&Type Type&Length.Type User.User&With
RaNgE&COnTeNT WITh CoNTENT-TypE tyPe                                        | Range&Content With Content-Type Type
BEgin COdE#uSeR#aGeNt.USeR                                                  | Begin Code#User#Agent.User
TypE LENGth                                                                 | Type Length
share|improve this answer
1  
Isn't l==l.swapcase the same as l<?0 (not tested)? At least for the input allowed for this task. –  Howard Dec 17 '13 at 15:59
    
Yes. Now that batman emphasized that no other separators have to be expected, indeed that is shorter. Thank you, @Howard. –  manatwork Dec 17 '13 at 16:19

Java - 209 characters

class C{
public static void main(String[]a){
for(String b:a){
char[]k=b.toLowerCase().toCharArray();
for(int i=-1;i<k.length;i++){if(i<0||"-. /&#".indexOf(k[i])>=0)k[++i]=(char)(k[i]-32);}
System.out.println(k);}}}

I added newlines only for readability.

share|improve this answer

C# – 110

A simple finite-state-machine-based processing:

x.Aggregate(new{b=1>0,r=""},(s,c)=>new{b="-. /&#".Contains(c),r=s.r+(s.b?Char.ToUpper(c):Char.ToLower(c))}).r

(where x is the string to capitalize)

and of course, if you want to be boring (after the specification was updated), you can use

new CultureInfo(9).TextInfo.ToTitleCase(x)

or, with all the boring boilerplate:

class C{static void Main(string[]a){System.Console.WriteLine(new System.Globalization.CultureInfo(9).TextInfo.ToTitleCase(a[0]));}}
share|improve this answer
    
Nah, won't compile as C# is no scripting language and you need to encapsulate this in a class. –  Pierre Arlaud Dec 17 '13 at 14:04
2  
Says who? Microsoft (R) Roslyn C# Compiler version 1.2.20906.1 Loading context from 'CSharpInteractive.rsp'. Type "#help" for more information. > "foobar".Aggregate(new{b=1>0,r=""},(s,c)=>new{b="-. /&#".Contains(c),r=s.r+(s.b?Char.ToUpper(c):Char.ToLower(c))}).r "Foobar" But if you really care about the boring boilerplate, add 112 characters of it. –  Mormegil Dec 17 '13 at 15:31
1  
You can cut the public and string[]a from the boilerplate –  Johnbot Dec 17 '13 at 17:34
    
Oh yeah, you’re right with public, but I need the arguments, as that is what I process… –  Mormegil Dec 18 '13 at 9:25

R, 143 116

A solution a bit long maybe but here we go:

f=function(x){a=sapply(1:nchar(x),function(y)substr(tolower(x),y,y));d=c(1,which(!a%in%letters)+1);a[d]=toupper(a[d]);cat(a,sep="")}

Slightly ungolfed and explained:

f <- function(x){
    #Split the string in characters and "lower-case" everything
    a <- sapply(1:nchar(x),function(y)substr(tolower(x),y,y))
    #Select the first character and each character following a 
    #character that doesn't belong to lower case alphabet
    d <- c(1,which(!a%in%letters)+1)
    #Make those ones uppercase.
    a[d] <- toupper(a[d])
    #Output (stdout) while pasting them back together.
    cat(a,sep="")
    }

Edit: 116 characters

The main challenge here is to vectorize substr. Here's another less verbose way.

f=function(x){n=1:nchar(x);a=mapply(substr,tolower(x),n,n);d=c(T,!a%in%letters);a[d]=toupper(a[d]);cat(a[n],sep="")}

Indented:

f <- function(x){
    n <- 1:nchar(x)
    a <- mapply(substr,tolower(x),n,n)
    d <- c(T,!a%in%letters) #This has been simplified as well
    a[d] <- toupper(a[d])
    cat(a[n],sep="") #Because a is now 1 char longer than x, need to subset a
    }

Usage:

> f("aGeNT ACcEpT/LEngTh-tYPe USeR raNgE.TyPe")
Agent Accept/Length-Type User Range.Type
share|improve this answer
    
You can save some characters. Since a consits of lowercase characters only, there's no need to check for matches with uppercase LETTERS. –  Sven Hohenstein Dec 18 '13 at 14:50
    
@SvenHohenstein indeed, thanks! –  plannapus Dec 18 '13 at 14:51
    
Another one: You can replace TRUE with T. –  Sven Hohenstein Dec 18 '13 at 14:53
    
Originally i had the tolower later. –  plannapus Dec 18 '13 at 15:02
    
OK, here's another one ;-) You can replace mapply(substr,tolower(x),n,n) with strsplit(tolower(x),"")[[1]] to save one character. –  Sven Hohenstein Dec 18 '13 at 15:30

Javascript 102

prompt().split(o=q='').map(function(c){o+=(q)?c.toLowerCase():c.toUpperCase(),q=('A'>c)?0:1})
alert(o)
share|improve this answer
    
You need no () around the ternary condition. Even more, you not need the second ternary: function(c){o+=q?c.toLowerCase():c.toUpperCase(),q='@'<c}. –  manatwork Dec 30 '13 at 9:34

Forth, 135

: s swap ;
: c 1 begin key dup 96 > if s if 32 - then 0 s 
else dup 64 > if s 0= if 32 + then 0 s then else 1 s then then emit again ; c

Translated output is written to stdout as it reads from stdin.

share|improve this answer

Befunge-98 (29), C (65)

Since the method/algorithm is pretty much the same, I include both versions in the same post. Both rely on keeping track of whether the last character was a symbol or letter, in order to know whether to lowercase a letter or not.

Befunge-98 (29)
#@~:'0` #v_,0>
',++@'% '<   ^
C (65)
c,d;main(){for(;~(c=getchar());d=c>48)putchar(c<48?c:c&95|32*d);}
share|improve this answer

Excel VBA-11 characters

In the Immediate window

?[Proper()]

VBscript

Set xlapp = CreateObject("excel.application")
wscript.echo xlapp.Evaluate("Proper(""BeGin/wITH.tyPE&conTeNt"")"
share|improve this answer
    
Could you provide some help on usage? I get “Compile error: External name not defined”. (In Word 2013 on the Developer tab I clicked Visual Basic, then in Visual Basic for Application I copy-pasted your code in the Immediate window and pressed Enter.) –  manatwork Dec 29 '13 at 13:29
    
@manatwork I should have clarified it was in Excel. You can do this from Word but the path is longer as you need to automate Excel. –  brettdj Dec 29 '13 at 13:34
1  
Cool. Works perfectly when VBA is started from Excel 2013. –  manatwork Dec 29 '13 at 13:47

PHP - 23 characters

mb_convert_case($w, 2);

It needs php_mbstring to work

share|improve this answer
    
On my 5.3.26 mb_convert_case("BeGin/wITH.tyPE&conTeNt", 2); returns “Begin/with.type&content”, not “Begin/With.Type&Content”. –  manatwork Dec 19 '13 at 14:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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