41
\$\begingroup\$

For today's challenge, you must write a program or function that alternates the case of a string. However, you must ignore non-alphabetic characters. This means that every alphabetic character must have a different case than the preceding and following alphabetic character. This is slightly more complex than uppercasing every other letter for example. If you take a string such as

hello world

and convert every other character to uppercase, you'll get:

hElLo wOrLd

As you can see, the lowercase o is followed by a lowercase w. This is invalid. Instead, you must ignore the space, giving us this result:

hElLo WoRlD

All non-alphabetic characters must be left the same. The output can start with upper or lowercase, as long as it consistently alternates. This means the following would also be an acceptable output:

HeLlO wOrLd

Your program should work regardless of the case of the input.

The input string will only ever contain printable ASCII, so you don't have to worry about unprintable characters, newlines or unicode. Your submission can be either a full program or a function, and you may take the input and output in any reasonable format. For example, function arguments/return value, STDIN/STDOUT, reading/writing a file, etc.

Examples:

ASCII                                   ->  AsCiI
42                                      ->  42
#include <iostream>                     ->  #InClUdE <iOsTrEaM>
LEAVE_my_symbols#!#&^%_ALONE!!!         ->  lEaVe_My_SyMbOlS#!#&^%_aLoNe!!!
PPCG Rocks!!! For realz.                ->  PpCg RoCkS!!! fOr ReAlZ.
This example will start with lowercase  ->  tHiS eXaMpLe WiLl StArT wItH lOwErCaSe
This example will start with uppercase  ->  ThIs ExAmPlE wIlL sTaRt WiTh UpPeRcAsE
A1B2                                    ->  A1b2

Since this is , standard loopholes apply and the shortest answer in bytes wins!

\$\endgroup\$
  • 32
    \$\begingroup\$ Ugh, I've only just realised this was that meme xD \$\endgroup\$ – Beta Decay May 25 '17 at 17:26
  • \$\begingroup\$ @BetaDecay Hahaha, that was not my intention. More just unfortunate timing. I though of it as a chat-mini-challenge, and I like the idea behind it because it's subtly harder than it seems. \$\endgroup\$ – DJMcMayhem May 25 '17 at 17:28
  • 4
    \$\begingroup\$ The next challenge is to print an ascii spongebob à la cowsay \$\endgroup\$ – Joe Frambach May 25 '17 at 19:41
  • 1
    \$\begingroup\$ Darn it! I just wrote a CJam script for this (as in yesterday) and deleted it. \$\endgroup\$ – Esolanging Fruit May 26 '17 at 1:58
  • 2
    \$\begingroup\$ There is some missed potential for the title or at least the examples using either penguin of doom or sporks. \$\endgroup\$ – Ian May 26 '17 at 6:00

33 Answers 33

19
\$\begingroup\$

JavaScript (ES6), 66 63 bytes

Starts with uppercase.

s=>s.replace(/[a-z]/gi,c=>c[`to${(s=!s)?'Low':'Upp'}erCase`]())

Test cases

let f =

s=>s.replace(/[a-z]/gi,c=>c[`to${(s=!s)?'Low':'Upp'}erCase`]())

console.log(f("ASCII"))
console.log(f("42"))
console.log(f("#include <iostream>"))
console.log(f("LEAVE_my_symbols#!#&^%_ALONE!!!"))
console.log(f("PPCG Rocks!!! For realz."))
console.log(f("This example will start with lowercase"))
console.log(f("This example will start with uppercase"))
console.log(f("A1B2"))

\$\endgroup\$
  • \$\begingroup\$ Exactly how I was going to do it. I think I can see where you can save a couple of bytes but I'm on my phone so can't test properly. \$\endgroup\$ – Shaggy May 25 '17 at 17:24
  • \$\begingroup\$ Yup, using a ternary is what I was going to suggest. \$\endgroup\$ – Shaggy May 25 '17 at 17:39
  • 1
    \$\begingroup\$ How does the s=!s trick work? \$\endgroup\$ – Cows quack May 25 '17 at 17:44
  • 7
    \$\begingroup\$ @KritixiLithos Because s is the input string, !s first evaluates to false (unless the input string is empty, in which case it would evaluate to true -- but an empty string will not generate any match anyway). After that, it just becomes a standard boolean operation, alternating between false and true. Also, we don't mind losing the content of s at this point because it was already used to feed .replace(). \$\endgroup\$ – Arnauld May 25 '17 at 17:49
  • 3
    \$\begingroup\$ @MayorMonty Unfortunately, that would match a few symbols. An input such as "A[I" would fail. \$\endgroup\$ – Arnauld May 25 '17 at 18:50
12
\$\begingroup\$

05AB1E, 11 8 bytes

Code:

lvyJ¤aiš

Uses the 05AB1E encoding. Try it online!

Explanation:

l           # Lowercase the input
 vy         # For each element..
   J        #   Join the entire stack into a single string
    ¤a      #   Check if the last character is alphabetic
      iš    #   If true, swapcase the entire string
\$\endgroup\$
  • \$\begingroup\$ I love how I try going in blind, knowing I have to beat 11-bytes; then slowly go from 17 to 11 bytes and realize lvy¾Fš}Da½J is exactly what you already had ._. \$\endgroup\$ – Magic Octopus Urn May 25 '17 at 18:18
  • 1
    \$\begingroup\$ @carusocomputing There is a much easier 8 byte solution :p \$\endgroup\$ – Adnan May 25 '17 at 18:21
  • 4
    \$\begingroup\$ oh, yeah, super easy haha. \$\endgroup\$ – Magic Octopus Urn May 25 '17 at 18:25
  • 2
    \$\begingroup\$ @Octopus There is some discussion about this, but I use both 'osable' and 'osabie'. \$\endgroup\$ – Adnan May 26 '17 at 8:00
  • 1
    \$\begingroup\$ @octopus I literally say Oh-Five-Ay-Bee-One-Eee, I am not a creative man. \$\endgroup\$ – Magic Octopus Urn Jun 13 '17 at 18:08
10
\$\begingroup\$

GNU Sed, 33

  • 5 bytes saved thanks to @TobySpeight

Score includes +1 for -r flag to sed.

s/([a-z])([^a-z]*.?)/\U\1\L\2/gi

Try it online.

\$\endgroup\$
8
\$\begingroup\$

Jelly, 13 bytes

nŒsTm2
ŒlŒuǦ

Try it online!

How it works

ŒlŒsǦ  Main link. Argument: s (string)

Œl      Cast to lowercase.
    Ǧ  At indices returned by the helper link...
  Œu        apply uppercase.


nŒsTm2      Helper link. Argument: s (string)

 Œs         Apply swapcase to s.
n           Perform vectorizing not-equal comparison.
   T        Compute the truthy indices.
    m2      Select every other one, starting with the first.
\$\endgroup\$
7
\$\begingroup\$

Japt, 16 14 bytes

r"%l"_m"uv"gT°

Try it online!

Explanation

r              // RegEx replace input
 "%l"          // [A-Za-z] as first arg to replace
     _         // created function Z=>Z as second arg to replace
       "uv"gT° // alternates "u" & "v"
      m        // map Z to either "u" upper or "v" lower
\$\endgroup\$
  • \$\begingroup\$ Very nice! You can remove the ,. Unless it's a number (i.e. [12]), Japt knows they're different items. I believe you can remove the &1 as well. \$\endgroup\$ – Oliver May 25 '17 at 18:11
  • \$\begingroup\$ Thanks @obarakon. The Japt documentation is a little sparse. \$\endgroup\$ – powelles May 25 '17 at 18:13
  • \$\begingroup\$ Thanks for using Japt. Feel free to ask questions, suggestions, etc. in the Japt chat room. There's also a Tips for Japt thread. :) \$\endgroup\$ – Oliver May 25 '17 at 18:16
  • \$\begingroup\$ _m"uv"gT° Nice. I was just about to suggest that. \$\endgroup\$ – Oliver May 25 '17 at 20:23
  • \$\begingroup\$ @obarakon Yeah I saw where ETH responded to your question in the chat and it got me trying things out. \$\endgroup\$ – powelles May 25 '17 at 20:32
6
\$\begingroup\$

Python 3, 86 76 68 66 63 bytes

-2 bytes thanks to DJMcMayhem
-3 bytes thanks to Cyoce

x=0
for i in input():print(end=(2*i).title()[x]);x^=i.isalpha()

Try it online! or Try all test cases

\$\endgroup\$
  • \$\begingroup\$ Two bytes shorter in python 3: Try it online! \$\endgroup\$ – DJMcMayhem May 25 '17 at 22:14
  • 1
    \$\begingroup\$ any reason you can't do print(end=(2*i).title()[x])? \$\endgroup\$ – Cyoce May 26 '17 at 3:50
5
\$\begingroup\$

Alice, 18 bytes

/olZlYuN
@iy.u..//

Try it online!

Explanation

This program follows a lesser-known template for odd-length programs that run entirely in ordinal mode. The linearized version of this code is:

il.l.uN.YuZyo@

Explanation of code:

i - push input onto stack            ["Hello world!"]
l - convert to lowercase             ["hello world!"]
. - duplicate                        ["hello world!", "hello world!"]
l - convert to lowercase (should be no-op, but avoids what seems to be a bug in the TIO implementation)
. - duplicate again                  ["hello world!", "hello world!", "hello world!"]
u - convert to uppercase             ["hello world!", "hello world!", "HELLO WORLD!"]
N - difference between sets          ["hello world!", "helloworld"]
. - duplicate reduced string         ["hello world!", "helloworld", "helloworld"]
Y - unzip (extract even positions)   ["hello world!", "helloworld", "hlool", "elwrd"]
u - convert to uppercase             ["hello world!", "helloworld", "hlool", "ELWRD"]
Z - zip evens back into string       ["hello world!", "helloworld", "hElLoWoRlD"]
y - perform substitution             ["hElLo WoRlD!"]
o - output                           []
@ - terminate

Without using l on the duplicate, the stack after N would be ["helloworld", "helloworld"]. I strongly suspect this is a bug.

\$\endgroup\$
5
\$\begingroup\$

C (tcc), 60 57 56 bytes

Thanks to DigitalTrauma for noticing bit 5 is the only difference for ASCII upper/lower case.

Special thanks to zch for golfing off three more bytes.

Save one more byte from RJHunter's idea

l;f(char*s){for(;*s=isalpha(*s)?*s&95|++l%2<<5:*s;s++);}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ I golfed it a bit more, and modified so it works on all of gcc, tcc, clang. FWIW, gcc puts string literals in read-only memory, so I used strdup() to get pointers to read-write memory in the test-driver code. \$\endgroup\$ – Digital Trauma May 25 '17 at 18:29
  • 1
    \$\begingroup\$ @DigitalTrauma thanks for that. I should have recognized bit 5 was the difference between upper and lower. Nice ! \$\endgroup\$ – cleblanc May 25 '17 at 18:38
  • \$\begingroup\$ I tried to make this version recursive too, but couldn't get it any shorter. \$\endgroup\$ – Digital Trauma May 25 '17 at 19:05
  • \$\begingroup\$ You can replace inner conditional with *s&~32|++l%2<<5 to save 3 bytes. \$\endgroup\$ – zch May 26 '17 at 10:18
  • \$\begingroup\$ Since the input promises to be printable ASCII, you can replace &~33 with &95 to save a further byte. \$\endgroup\$ – RJHunter May 26 '17 at 23:59
4
\$\begingroup\$

Java 8, 99 bytes

a->{String r="";int i=0;for(int c:a)r+=(char)(c>64&c<91|c>96&c<123?i++%2<1?c|32:c&~32:c);return r;}

Explanation:

Try it here.

a->{                          // Lambda with char-array parameter and String return-type
  String r="";                //  Result-String
  int i=0;                    //  Flag for alteration
  for(int c:a)                //  Loop over the characters of the input
    r+=(char)                 //   And append the result-String with the following (converted to char):
      (c>64&c<91|c>96&c<123?  //    If it's a letter:
       i++%2<1?               //     And the flag states it should be lowercase:
        (c|32)                //      Convert it to lowercase
       :                      //     Else (should be uppercase):
        (c&~32)               //      Convert it to uppercase
      :                       //    Else:
       c);                    //     Simply append the non-letter character as is
                              //  End of loop (implicit / single-line body)
  return r;                   //  Return result-String
}                             // End of method
\$\endgroup\$
  • \$\begingroup\$ I couldn't get it shorter but you might be able to use (c+"").matches("[A-Za-z]") or Character.isLetter(c) to save bytes. \$\endgroup\$ – TheLethalCoder May 26 '17 at 11:31
  • \$\begingroup\$ @TheLethalCoder Both are longer than c>64&c<91|c>96&c<123 though. And since the I use int anyway for the Character.toUpperCase(...) and Character.toLowerCase(...) golfed parts (these: (char)(c&~32) and (char)(c|32)), I doubt I could make it shorter with either of those. \$\endgroup\$ – Kevin Cruijssen May 26 '17 at 11:54
  • 1
    \$\begingroup\$ I thought you wouldn't be able to but worth posting to see if you could make use of them anyway \$\endgroup\$ – TheLethalCoder May 26 '17 at 11:56
  • \$\begingroup\$ @TheLethalCoder Ah ok. :) In some cases the first might help with a slightly different approach for other challenges, but for this challenge it's shorter as is. Thanks anyway. \$\endgroup\$ – Kevin Cruijssen May 26 '17 at 12:05
  • \$\begingroup\$ a->{String r="";int i=0,f=32;for(int c:a)r+=(char)(c>64&c<91|c>96&c<123?(f=~f):c);return r;} ?? \$\endgroup\$ – Roman Gräf May 26 '17 at 13:25
4
\$\begingroup\$

Ruby, 57 55 47 41 bytes

Byte count includes two bytes for command line options.
Run it for example like this: $ ruby -p0 alternate_case.rb <<< "some input"

gsub(/\p{L}/){($&.ord&95|32*$.^=1).chr}

With the p0 option, the entire input is consumed in one go, and the magical global $. is incremented to 1. This is later toggled between 0 and 1 and used for keeping the state.

Works with multiline input; Try it online!

Thanks to Ventero for amazing input -- check the comments for details.

\$\endgroup\$
  • 1
    \$\begingroup\$ Man, if it weren't for the fact that $. auto-increments with each gets call, a full program with the -p flag would've been shorter... \$\endgroup\$ – Value Ink May 25 '17 at 20:51
  • 1
    \$\begingroup\$ 1&$.+=1 allows you to drop the parentheses. And for completeness' sake, there is another global integer - it's unfortunately just read-only: $$. \$\endgroup\$ – Ventero May 25 '17 at 22:47
  • 1
    \$\begingroup\$ Another thing about the command line flag: -p0 makes the interpreter read all available input in one go - so your code is only invoked once, allowing you to freely use $.. Combining that with the fact that gsub implicitly operates as $_.gsub! when specifying -p makes a full program significantly shorter: 48 characters for gsub(/[a-z]/i){[$&.upcase,$&.downcase][1&$.+=1]} and 2 for the p0 flag. \$\endgroup\$ – Ventero May 25 '17 at 22:56
  • 1
    \$\begingroup\$ Final remark, I promise :) Once you're using -p0, you can actually save a few more characters in how you flip $. back and forth: Since it's now guaranteed to be 1 when your code is invoked, you can simply use $.^=1. \$\endgroup\$ – Ventero May 25 '17 at 23:04
  • 2
    \$\begingroup\$ Turns out I lied, I have another comment :D As the input is guaranteed to only ever contain printable ASCII, we can use Ruby's support for Unicode categories in regular expressions: /\p{L}/ (Unicode category Letter) is one character shorter than /[a-z|/i. \$\endgroup\$ – Ventero May 25 '17 at 23:24
3
\$\begingroup\$

Brachylog, 25 bytes

{ḷ|ụ}ᵐ.{ḷ∈Ạ&}ˢ¬{s₂{∈Ạ}ᵐ}∧

Try it online!

This is both long and slow.

Explanation

{   }ᵐ.                       The Output is the result of mapping on each char of the Input:
 ḷ                              Lowecase the char
  |                             Or
   ụ                            Uppercase the char
       {    }ˢ                In the Ouput, select the chars that:
        ḷ∈Ạ&                    when lowercased are in "abc...xyz" (ie are letters)
              ¬{       }∧     In that new string, it is impossible to find:
                s₂              a substring of 2 consecutive chars
                  {∈Ạ}ᵐ         where both of them are in the lowercase alphabet
\$\endgroup\$
3
\$\begingroup\$

MATL, 16 15 bytes

Xktkyy-f2L))5M(

Try it online! Or verify all test cases.

Explanation

Consider input 'hello world'

Xk    % To upper case
      % STACK: 'HELLO WORLD'
t     % Duplicate top element
      % STACK: 'HELLO WORLD', 'HELLO WORLD'
k     % To lower case
      % STACK: 'HELLO WORLD', 'hello word'
yy    % Duplicate top two elements
      % STACK: 'HELLO WORLD', 'hello word', 'HELLO WORLD', 'hello word'
-     % Difference (of code points; element-wise)
      % STACK: 'HELLO WORLD', 'hello word', [-32 -32 -32 -32 -32 0 -32 -32 -32 -32 -32]
f     % Indices of nonzeros
      % STACK: 'HELLO WORLD', 'hello word', [1 2 3 4 5 7 8 9 10 11]
2L)   % Keep only even-indexed values (*)
      % STACK: 'HELLO WORLD', 'hello word', [2 4 7 9 11]
)     % Reference indexing (get values at indices)
      % STACK: 'HELLO WORLD', 'elwrd'
5M    % Push (*) again
      % STACK: 'HELLO WORLD', 'elwrd', [2 4 7 9 11]
(     % Assignment indexing (write values at indices). Implicit display
      % STACK: 'HeLlO wOrLd

'

\$\endgroup\$
3
\$\begingroup\$

Perl 6,  32  30 bytes

{S:g/<:L><-:L>*<:L>?/$/.tclc()/}

Try it

{S:g{<:L><-:L>*<:L>?}=$/.tclc}

Try it

Expanded:

{  # bare block lambda with implicit parameter 「$_」

  S            # string replace (not in-place) implicitly against 「$_」

  :global

  {

    <+ :L >    # a letter
    <- :L >*   # any number of non-letters
    <+ :L >?   # an optional letter

  }

  =

  $/.tclc()    # uppercase the first letter, lowercase everything else
}
\$\endgroup\$
3
\$\begingroup\$

q/kdb+, 51 42 38 bytes

Solution:

{@[x;;upper]1#'2 cut(&)x in .Q.a}lower

Example:

q){@[x;;upper]1#'2 cut(&)x in .Q.a}lower"hello world"
"HeLlO wOrLd"

Notes:

.Q.a        // abcde...xyz lowercase alphabet
(&) x in    // where, returns indices for where x (hello world) is an alpha
2 cut       // splits list into 2-item lists
1#'         // takes first item of each 2-item list; ie the indices to uppercase
@[x;;upper] // apply (@) upper to x at these indices
\$\endgroup\$
2
\$\begingroup\$

V, 17, 13 bytes

VUÍშáü$©/ì&

Try it online!

Or Verify all test cases!

HeXdUmP:

00000000: 5655 cde1 83a8 e1fc 24a9 2fec 26         VU......$./.&

Explanation:

This uses a compressed regex™️, so before explaining it, let's expand the regex out:

:%s/\v\a.{-}(\a|$)/\l&

The VU converts everything to uppercase. Then we run this:

:%                      " On every line:
  s/\v                  "   Substitute:
      \a                "     A letter
        .{-}            "     Followed by as few characters as possible
            (\a|$)      "     Followed by either another letter or an EOL
                  /     "   With:
                   \l   "     The next character is lowercased
                     &  "     The whole text we matched

Old/more interesting answer:

:se nows
Vuò~h2/á
\$\endgroup\$
2
\$\begingroup\$

PHP, 71 Bytes

for(;a&$c=$argn[$i++];)echo ctype_alpha($c)?(ul[$k++&1].cfirst)($c):$c;

Try it online!

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

CJam, 26 24 bytes

qeu{_'[,65>&,T^:T{el}&}%

Try it online!

Explanation

q         e# Read all input.
eu        e# Uppercase it.
{         e# For each character:
 _        e#  Duplicate it.
 '[,65>&  e#  Set intersection with the uppercase alphabet.
 ,        e#  Length (either 0 or 1 in this case).
 T^:T     e#  XOR with T (T is initially 0), then store the result back in T.
 {el}&    e#  If The result of the XOR is true, lowercase the character.
}%        e# (end for)
\$\endgroup\$
2
\$\begingroup\$

Pyth, 11 bytes

srR~xZ}dGrZ

Try it here

Explanation

              # Z = 0; Q = eval(input())
srR~xZ}dGrZQ  # Auto-fill variables
         rZQ  # lowercase the input
 rR           # Apply the r function to each letter of the input with
   ~xZ}dG     # ... this as the other argument
   ~          # use the old value of the variable Z, then update it with the value of ...
    xZ        # Z xor ...
      }dG     # the variable d is a lowercase letter
              # because of how mapping works in pyth, d will contain the current letter
              # This causes Z to flip between 0 and 1, alternately upper and lower casing
              # the current character if it is a letter
\$\endgroup\$
2
\$\begingroup\$

PowerShell, 86 bytes

-join($args[0]|%{if($_-match"[a-z]"-and($i=!$i)){"$_".toupper()}else{"$_".tolower()}})

Input is a [char[]] array.

Comments in code for explanation

# Join the array of string and char back together.
-join
    # Take the first argument and pass each element ([char]) down the pipe. 
    ($args[0]|%{
        # Check if this is a letter. Second condition is a boolean that changes at every pass 
        # but only if the current element is a letter. If not the condition never fires
        if($_-match"[a-z]"-and($i=!$i)){
            # Change the character to uppercase
            "$_".toupper()
        }else{
            # Output the character to lowercase. 
            # Special characters are not affected by this method
            "$_".tolower()
        }
    })
\$\endgroup\$
2
\$\begingroup\$

Haskell, 105 83 + 2 4 + 1 byte of separator = 108 86 88 Bytes

import Data.Char
f#(x:y)|isLetter x=([toUpper,toLower]!!f)x:(1-f)#y|1>0=x:f#y
_#l=l

Function is (1#), starts lowercase. Try it online!

The sad thing is that this is longer than the Java and C# answers Thanks to Ørjan Johansen for saving 22 bytes by merging three lines into one!

\$\endgroup\$
  • 2
    \$\begingroup\$ I saw it needed those long imported functions so I didn't even try... but that's a bit much, you can merge some lines: f#(x:y)|isLetter x=([toUpper,toLower]!!f)x:(1-f)#y|1>0=x:f#y \$\endgroup\$ – Ørjan Johansen May 29 '17 at 2:29
  • \$\begingroup\$ Sorry for nitpicking, but I think 1# does not count as an anonymous function. In my understanding, one should be able to bind an anonymous function to an identifier, but e.g. f=1# won't work. Instead you need the section (1#) for +2 bytes. This is also implicitly stated in our community guidelines for golfing in Haskell, though maybe those should be adapted to explicitly mention this case. \$\endgroup\$ – Laikoni May 29 '17 at 9:14
  • \$\begingroup\$ @Laikoni ok, answer updated \$\endgroup\$ – Generic Display Name May 29 '17 at 13:43
2
\$\begingroup\$

Google Sheets, 264 bytes

=ArrayFormula(JOIN("",IF(REGEXMATCH(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1),"[A-Za-z]"),CHAR(CODE(UPPER(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1)))+MOD(LEN(REGEXREPLACE(LEFT(A1,ROW(OFFSET(A1,0,0,LEN(A1)))),"[^A-Za-z]","")),2)*32),MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1))))

It's a big mess but it's a little easier if you expand it out:

=ArrayFormula(
  JOIN(
    "",
    IF(REGEXMATCH(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1),"[A-Za-z]"),
      CHAR(
        CODE(UPPER(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1)))
        +
        MOD(LEN(REGEXREPLACE(LEFT(A1,ROW(OFFSET(A1,0,0,LEN(A1)))),"[^A-Za-z]","")),2)*32
      ),
      MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1)
    )
  )
) 

The pseudo-logic would run like this:

For each character {                                    // ArrayFormula()
  If (character is a letter) {                          // REGEXMATCH(MID())
    Return CHAR(                                        // CHAR()
      CODE(UPPER(letter))                               // CODE(UPPER(MID()))
      +
      If (nth letter found and n is odd) {32} else {0}  // MOD(LEN(REGEXREPLACE(LEFT())))
    )
  } else {
    Return character                                    // MID()
  }
}
\$\endgroup\$
2
\$\begingroup\$

Perl 5, 24 bytes

23 bytes + 1 byte for -p.

Thanks to @Dada for -2 bytes.

s/\pl/--$|?uc$&:lc$&/eg

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Neat. \pl instead of [a-z] to 2 bytes tho :) \$\endgroup\$ – Dada Jul 6 '17 at 11:59
  • \$\begingroup\$ @Dada, I genuinely didn't know that! How didn't I know that!! Thank you! \$\endgroup\$ – Dom Hastings Jul 6 '17 at 12:06
  • \$\begingroup\$ I think I learned it from Ton Hospel, and I use it now and then (actually I tend to forget about it too often and use [a-z] instead!). If you wonder, it comes from perlrecharclass ;) \$\endgroup\$ – Dada Jul 6 '17 at 12:09
1
\$\begingroup\$

Retina, 46 bytes

T`L`l
T`l`L`.(?=([^a-z]*|[a-z][^a-z]*[a-z])*$)

Try it online! Includes test cases.

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

C 64 bytes

B;R(char *s){for(;*s=isalpha(*s)?(B=!B)?*s|=32:*s&=~32:*s;s++);}

Takes advantage of ascii encoding where upper and lower case letters are offset by 0x20.

\$\endgroup\$
  • \$\begingroup\$ You don't need the ' ' space between char and *s \$\endgroup\$ – cleblanc May 25 '17 at 19:03
  • \$\begingroup\$ This looks very similar to @cleblanc's answer. \$\endgroup\$ – Digital Trauma May 25 '17 at 19:08
  • \$\begingroup\$ I posted it when @cleblanc's post used toUpper() and toLower(). \$\endgroup\$ – user230118 May 25 '17 at 19:39
  • 1
    \$\begingroup\$ My comment suggesting this approach was at 18:29:34Z. cleblanc's edit to incorporate this was at 18:37:36Z. Your answer was posted at 18:38:21Z. So I guess cleblanc's answer was less than a minute before your post. Your answer is remarkably similar to my suggestion, but I guess that's the nature of code-golf - often solutions in the same language will converge to the same thing - so I'll let it slide :) \$\endgroup\$ – Digital Trauma May 26 '17 at 0:15
1
\$\begingroup\$

Retina, 32 bytes

T`l`L
01T`L`l`[A-Z][^A-Z]*[A-Z]?

Try it online!

First converts the input to uppercase, and then groups the input into matches containing up to two capital letters. The only time it will contain only one letter is if the last letter doesn't have a pair. Then it lowercases the first letter of each of these matches.

The 01 in the second stage translates roughly to: do not change the behaviour of this stage based on the match number, but only apply the changes to the first character of each match.

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

PHP 5, 54 bytes

<?=preg_filter('/\pL/e','($0|" ")^a^aA[$i^=1]',$argn);
\$\endgroup\$
1
\$\begingroup\$

C#, 100 bytes

s=>{var r="";int m=0;foreach(var c in s)r+=char.IsLetter(c)?(char)(++m%2>0?c|32:c&~32):c;return r;};
\$\endgroup\$
1
\$\begingroup\$

Groovy, 79 bytes

{x=0;it.toUpperCase().collect{(it==~/\w/)?x++%2?it:it.toLowerCase():it}.join()}
\$\endgroup\$
1
\$\begingroup\$

Python 3, 192 bytes

x=list(input())
s=[]
for i in x[1::2]:
 s.append(i)
 x.remove(i)
s.reverse()
while len(x)<len(s):
 x.append("")
while len(x)>len(s):
 s.append("")
for i in range(len(x)):
 print(end=x[i]+s[i])

Try it online!

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

Convex, 16 bytes

¯{_U&,R^:R{¬}&}%

Try it online!

Convex port of @Business Cat's answer.

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