# Challenge :

Given a string split at specific positions and capitalize the first character of the given word. Capitalize the first word's first char if and only if it was already capitalized

# Input :

A string s and a character c.

# Ouput :

The string with each occurrence of c replaced with the first char capitalized

# Examples :

STRING(s)             CHARACTER(c)  RESULT
Hello_world           _             HelloWorld
me,no,like            ,             meNoLike
you-got-it            -             youGotIt
Am^I^clear            ^             AmIClear
go!full!caps          !             goFullCaps
weird&but&tRue        &             weirdButTRue
ProbleM1fixed1no      1             ProbleMFixedNo
!prob!!lem!s!Olved!!  !             ProbLemSOlved


# Note :

• Given input will always be valid. i.e : The first will always be a string with at least one instance of the character to replace at. The second will always will be a single character.
• The length of the input string will be greater 4.
• There will be at least one occurrence of the character to split at.

• The input is guaranteed to contain only letters and the separator (Thanks @Arnauld)

• Separator is anything that is not an alphabet (a-z / A-Z) (suggested by @Dennis)

# Winning criteria :

This is so shortest code in bytes for each language wins.

1. Thanks to @JonathanAllan for pointing out two mistakes.
• Tips when creating test cases: Make each one cover at least one corner case. All your test cases are basically identical (maybe except the one with 1). Try to think about how solutions might fail, and make a test case for such situations. Some examples: Letters as separators, the separator being the last character, consecutive separators and so on. There's no need to have many test cases that doesn't test different things. – Stewie Griffin May 12 '18 at 16:11
• You're missing a delimiter in the last test case - there should be a ! there. I would edit it myself, but there's not enough characters for me to do it. – ollien May 13 '18 at 13:11
• I've downvoted this due to the multiple changes to the spec. On a sidenote, you need to make mention a lot sooner than the last test case that the string may contain 2 or more consecutive "separators" and that we are not guaranteed that a letter will always follow a "separator". – Shaggy May 13 '18 at 15:55
• I looked it up: Stewie didn't suggest any test cases, but he asked whether the first or last character could be a separator and whether there could be consecutive separators. In the future, please consider using the sandbox to get all these details sorted out before going live. It's frustrating to get your answer invalidated because of changes in the specification. The most surprising of all is the restriction to take the character as input, even if the program doesn't need it. That makes no sense at all. – Dennis May 13 '18 at 16:22
• Can we have a test-case with separator ., I can imagine some string splitting functions struggling with that one. – JAD May 14 '18 at 8:15

# Python 3, 63 bytes

lambda s,c:''.join(map(min,s,s[0]+s.title()[1:])).replace(c,'')


Try it online!

# C (gcc), 6153 55 bytes

-8 bytes thanks to Dennis!

f(s,c)char*s;{for(;*s;putchar(*s++))if(*s==c)*++s&=95;}


Try it online!

• Suggest *s==c?*++s&=95:0; instead of if(*s==c)*++s&=95; – ceilingcat Dec 7 '18 at 20:44

# JavaScript (ES6), 58 56 bytes

Saved 2 bytes thanks to @l4m2 / @Downgoat

Takes input in currying syntax (s)(c).

s=>c=>s.replace(u=/./g,x=>u=x==c?'':u?x:x.toUpperCase())


Try it online!

### Commented

s => c =>                  // given s and c
s.replace(u = /./g, x => // initialize u to a RegExp; replace each character x in s with,
u =                    // and update u to:
x == c ?             //   if x is the separator:
''                 //     an empty string
:                    //   else:
u ?                //     if u is not an empty string:
x                //       x unchanged
:                  //     else:
x.toUpperCase()  //       x capitalized
)                        // end of replace()

• consolation 56 bytes for s=>c=>s.replace(RegExp(c+".","g"),m=>m[1].toUpperCase()), since it doesn't work for special regex characters – Conor O'Brien May 13 '18 at 4:20
• 50 bytes. Or 47 if you don't bother taking the second input, which is irrelevant. – Shaggy May 13 '18 at 15:06
• @Shaggy Thanks! I've added it as a separate version, since the new rules are quite different from the original ones. – Arnauld May 13 '18 at 15:20
• fail !prob!!lem!s!Olved!! – l4m2 May 13 '18 at 15:32
• @l4m2, that's a new test case which changes the spec yet again. A + before the . in the RegEx will get around it. – Shaggy May 13 '18 at 15:53

(?=.*(.)$)\1  Try it online! Link includes test suite. Assumes the input consists of the string and character concatenated together. Explanation: The first stage transliterates all characters immediately following occurrences of the end character from lower to upper case and the second stage then deletes all occurrences of the end character. For both solutions, using a right-to-left match instead of a + also works. • Since the input is guaranteed to only contain alphabetic characters and the separator, you can use [^a-z] instead of the lookaheads Try it online! – Kritixi Lithos May 13 '18 at 9:23 # APL (Dyalog Classic), 22 bytes {⍵~⍨1(819⌶@(⍵=¯1⌽⊢))⍺}  Try it online! # Röda, 57 54 bytes -3 bytes thanks to Cows quack {(_/\Q$_)|{pull;[upperCase(_[:1]),_1[1:]]if[#_1>0]}}


Try it online!

Explanation:

{
(_/\Q$_)| /* Pull two strings and split the first with the second */ { pull; /* Pull one string and print it */ /* For each string _1 in the stream: */ /* If _1 is not empty: */ [ /* Print: */ upperCase(_[:1]), /* The first character capitalized */ _1[1:] /* The rest of characters */ ]if[#_1>0] /* End if */ } }  • You can leave out the \E from the regex, and _[0:1]_[:1] – Kritixi Lithos May 12 '18 at 17:49 # V, 6 7 bytes 1 byte saved by not using argument ÓÁˆ/õ±  Try it online! The program takes in the text as input and the char as an argument. Hexdump: 00000000: d3c1 882f f5b1 .../..  This is a simple substitution. Uncompressed, it looks like the following :s/\A(.)/\u\1/g  Perform a global substitution in which \A, a non-alphabetic character, followed by a character (.) is replaced with uppercased \u first capture group \1 • Doesn't work for input where c is a special regex character – Conor O'Brien May 13 '18 at 4:24 • @ConorO'Brien Fixed, and thanks to this I found a shorter solution :D – Kritixi Lithos May 13 '18 at 9:06 # Scala, 83 bytes def f(s:String)={val w=s.split("[^a-zA-Z]");w(0)+w.tail.map(_.capitalize).mkString}  Try it online! Explanation: def f(s: String) = { // takes a String "s" as input val w = s.split("[^a-zA-Z]"); // split on non-alpha chars w(0) + w.tail.map(_.capitalize).mkString // upper case first letter of all words except first one and join array into a String } //  # Red, 87 bytes func[s c][b: split s c prin b/1 foreach w next b[if w <>""[w/1: uppercase w/1 prin w]]]  Try it online! # 05AB1E, 9 bytes ¡ćsvyćusJ  Try it online! Explanation ¡ # split the string on the char ć # extract the head of the resulting list s # swap the head to the bottom of the stack vy # for each string y in the rest of the list ću # extract the head and capitalize it s # swap it below the rest of the string J # join everything to one string  # PHP, 91 83 bytes $a=explode($argv[2],$argv[1]);echo array_shift($a);foreach($a as$i)echo ucfirst($i);


Run with -r. Was 2 bytes shorter using split instead of explode, but ^ test fails due to regex.

-8 thanks to Med

• You can remove {and } from the for loop, it will only treat the next statement as body of the condition. – Med May 14 '18 at 10:01
• You can even do the echo inside the loop: $a=explode($argv[2],$argv[1]);echo array_shift($a);foreach($a as$i)echo ucfirst($i); – Med May 14 '18 at 10:15 ## Groovy, 43 bytes, 45 bytes s.replaceAll(/\$c(.)/){it[1].toUpperCase()}


Try it online. Test suite included excluding the last item as it lacks the separator char c.

# Go, 13892 87 bytes

Dropped 46 bytes thanks to @Dennis' title case idea.

func f(s,d string){p:=Split(s,d);Print(p[0]+Replace(Title(Join(p[1:]," "))," ","",-1))}


Try it online!

# Husk, 10 bytes

ΣΓ·:mΓo:ax


Try it online!

### Explanation

ΣΓ·:mΓ(:a)x  -- example inputs: 'x' "abxbcxcdxdex"
x  -- split on character: ["ab","bc","cd","de"]
Γ           -- pattern match (x = head) (xs = tail) and do..
·:         -- | construct list (x:xs) but with the second argument do..
m        -- | | map (eg. "bc")
Γ(  )   -- | | | pattern match on first character
( a)   -- | | | | upper-case it
(: )   -- | | | | and join again
-- | | | : "Bc"
-- | | : ["Bc","Cd","De"]
-- : ["ab","Bc","Cd","De"]
Σ            -- concatenate: "abBcCdDe"


# F# (Mono), 122 bytes

let f(s:string)c=s|>Seq.mapi(fun i x->if i>0&&s.[i-1]=c then Char.ToUpper(x)else x)|>Seq.where((<>)c)|>Seq.toArray|>String


Try it online!

# Java 10, 141 bytes

s->c->{var r=s.split("\\"+c);var r=a[0],t;for(int i=0;++i<a.length;r+=t.isEmpty()?"":(char)(t.charAt(0)&~32)+t.substring(1))t=a[i];return r;}


Try it online.

Explanation:

s->c->{                    // Method with String and character parameters and String return-type
var r=s.split("\\"+c);   //  Split String by character (with potential regex char)
var r=a[0],              //  Result-String, starting at the first item
t;                   //  Temp-String to reduce bytes
for(int i=0;++i<a.length;//  Loop in the range [1, length_of_array)
r+=                  //    After every iteration: append the result-String with:
t.isEmpty()?      //     If the current item empty:
""               //      Append nothing
:                 //     Else:
(char)(t.charAt(0)&~32)
//      Capitalize the first character
+t.substring(1)) //     And append the other characters as is
t=a[i];                //   Set t to the current String-item of the array
return r;}               //  Return the result-String


# R, 87 bytes

g<-function(s,x,z=strsplit(s,x,T)[[1]])cat(z[1],capwords(z[-1]),sep="")
example(chartr)


Try it online!

Uses this trick can can not be properly executed in TIO so I simulated it.

We need the T otherwise one of the test cases fails.

# Stax, 11 bytes

óKo{cplòüö\


Run and debug it

Explanation

/BsF1:/s^s|dl                 # Full Program, unpacked, Implicit Input
/                             # Split on substrings (Split input with symbol to split on)
B                            # Remove first element from array. Push the tail of the array, then the removed element.
s                           # Swap first two elements of stack
F                          # Start for loop
1:/                       # Split array at index; push both parts.
s^s                    # Swap first two elements of stack, capitalize character, swap first two elements
|dl                  # Get length of stack, listify that amount (entire stack), implicit output of array


There's a few parts I would really like to fix somehow. I can get it down to about 8 bytes, but it fails on the last test case >.<

# Ruby-pl, 36 bytes

$_.gsub!(/[^a-z]+(.|$)/i){$1.upcase}  Try it online! Takes only the string without second argument. Uses the block version of gsub! method because with common gsub! x,y syntax $1 is not readily filled with match data. |\$ in regex is necessary for the test case with separator in the end.

# Python 3, 77 bytes

o=[]
for x in s.split(c): o.append(chr(ord(x[0])-32)+x[1:])
print(''.join(o))


Try it online!

This assumes that the string is ASCII encoded and assumes that s and c are preloaded variables containing the input.

for x in s.split(x)       #loop through items in the string s split by x
o.append(             #add the following to c
chr(              #turn the following number into a character
ord(          #turn the following character into a number
x[0]      #the first character in string x
)-32          #subtract 32 from this number
+x[1:]            #add everything past and including the second character in string x


This solution works on the fact that in ASCII encoding, lowercase letters are positioned 32 entries after capitalised letters

Edit: i just realised that this also capitalises the first character in the string, which it shouldn't. but i'm quite proud of my nonsense, so i'll leave this up if that's allowed

• What is s supposed to be ? – Muhammad Salman Jun 6 '18 at 9:52
• @MuhammadSalman A string s and a character c.  – Davin Miler Jun 6 '18 at 9:53
• Lovely, make it work, Go here and see if it works or not : TIO. When it does tell me ? – Muhammad Salman Jun 6 '18 at 9:55
• oops! i just realised i made a mistake when changing the variable names, c=[] is supposed to be any other variable – Davin Miler Jun 6 '18 at 9:57
• @MuhammadSalman here – Davin Miler Jun 6 '18 at 10:00