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.


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!

  • 37
    \$\begingroup\$ Ugh, I've only just realised this was that meme xD \$\endgroup\$
    – Beta Decay
    Commented May 25, 2017 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
    Commented May 25, 2017 at 17:28
  • 4
    \$\begingroup\$ The next challenge is to print an ascii spongebob à la cowsay \$\endgroup\$
    – 000
    Commented May 25, 2017 at 19:41
  • 1
    \$\begingroup\$ Darn it! I just wrote a CJam script for this (as in yesterday) and deleted it. \$\endgroup\$ Commented May 26, 2017 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
    Commented May 26, 2017 at 6:00

41 Answers 41


Acc!!, 110 bytes

Count i while _/256 {
Write _/8+32*(_%4/3-_%8%5/4)

Try it online!


Set toLower flag to 0
Read a character
While not EOL:
  Calculate isUpper and isLower flags
  If isUpper && toLower, output (character + 32)
  If isLower && !toLower, output (character - 32)
  Else, output character unchanged
  If isUpper or isLower, toggle toLower
  Reset isUpper and isLower, and read a new character

Accumulator partitioning

We reserve the lowest three bits of the accumulator for storing the flags: toLower in the 1's place, isUpper in the 2's place, and isLower in the 4's place. The rest of the accumulator, at the 8's place and above, stores the input character.

For example, with input of Hello World, after reading the H and calculating flags, the accumulator has a value of 578, or in binary:

1001000 0 1 0
   |    | | \-> toLower (false)
   |    | \---> isUpper (true)
   |    \-----> isLower (false)
   \----------> ASCII code for 'H'

After reading the space, the accumulator is 257:

0100000 0 0 1
   |    | | \-> toLower (true)
   |    | \---> isUpper (false)
   |    \-----> isLower (false)
   \----------> ASCII code for ' '


Line 1


Stores the first input character and sets all the flags to 0.

Line 2

Count i while _/256 {

Loops while the accumulator value is >= 256 (i.e. the character's ASCII code is at least 32).

Line 3


Calculates the isUpper and isLower flags. The main trick here is using integer division for the inequalities. For example, if x is a printable-ASCII code, then 65 <= x is equivalent to x/65 with integer division: values smaller than 65 become 0, values between 65 and 126 become 1, and we don't have to worry about anything larger than 126. We can use this approach for all four inequalities (keeping in mind that the ASCII codes are all multiplied by 8 in the accumulator).


65 <= char <= 90
65*8 <= acc <= 90*8+7
acc/520 == 1 && 727/acc == 1

Expression: _/520*(727/_)


97 <= char <= 122
97*8 <= acc <= 122*8+7
acc/776 == 1 && 983/acc == 1

Expression: _/776*(983/_)

This line, then, takes the accumulator and adds isUpper*2 + isLower*4 to it.

Line 4

Write _/8+32*(_%4/3-_%8%5/4)

Outputs the character, swapping case if necessary.

There are two instances in which we need to modify the ASCII value before output:

  1. isUpper is 1, toLower is 1
    • We need to convert the uppercase letter to lowercase by adding 32
    • The three flag bits are 011, i.e. acc%4 == 3
  2. isLower is 1, toLower is 0
    • We need to convert the lowercase letter to uppercase by subtracting 32
    • The three flag bits are 100, i.e. acc%8 == 4

We can simulate the equality test using mod and int-div. For example, acc%8 == 4 is equivalent to acc%8%5/4:

acc%8      0 1 2 3 4 5 6 7
     %5    0 1 2 3 4 0 1 2
       /4  0 0 0 0 1 0 0 0

This line, therefore, takes 1 if we need to convert upper-to-lower, subtracts 1 if we need to convert lower-to-upper, multiplies that by 32, adds it to the ASCII code, and outputs it.

Line 5


Toggle the toLower flag if necessary; inputs and stores a new character.

We need to toggle toLower if the character was a letter, i.e. either isUpper or isLower was set. The possible flag bit values are 010, 011, 100, and 101--i.e. 2 through 5 (note that 6 and 7 are not possible because a letter can't be both upper- and lowercase). This expression gives 1 for those values and 0 otherwise:

 _%8       0 1 2 3 4 5
    +2     2 3 4 5 6 7
(     )/4  0 0 1 1 1 1

Call this value isLetter. Then we want the new value of toLower to be toLower XOR isLetter (if isLetter is true, swap the value of toLower; otherwise, leave it unchanged). We can do XOR by adding the two values mod 2. Finally, we also read another character with N, multiply it by 8, and add it in.


Japt v2.0a0, 11 10 bytes


Try it


MUMPS, 98 bytes

 f i=1:1:$l(s) s c=$e(s,i) s:c?1A u=c?1U,f=$s(f="":u,1:'f),$e(s,i)=$c(2*f-1*-'(f=u)*32+$a(c))
 w s

Try it online!

  • f i=1:1:$l(s): Set i=1 and loop over this line of code until i reaches the length of the input string s (inclusive). i is incremented by 1 each loop.

  • s c=$e(s,i): Assign the ith character of s to c using the $extract function.

  • s:c?1A: Execute the following set statements if c is an alphabetical character (uppercase or lowercase). This line and the next use M's built-in string matching system.

  • u=c?1U: Make u a boolean storing whether c is an uppercase character. There is only one data type in M so u's value will be 1 for true or 0 for false.

  • f=$s(f="":u,1:'f): Make f a boolean storing whether c should be an uppercase character. f's value will also be 1 or 0. It's assigned u if this is the first alphabetic character because the first alphabetic character is in the right case by definition. Otherwise its value is flipped from its previous value using the not operator '.

  • $e(s,i)=$c(2*f-1*-'(f=u)*32+$a(c)): The left-hand side is the ith character of s again; we're setting it equal to the right-hand side which modifies s itself. $a (for $ascii) and $c (for $char) are inverses: the former converts characters to the corresponding ASCII number and the latter converts numbers back into characters. The argument of $c is a compact way to add 32 to $a(c) if c is lowercase but should be uppercase, subtract 32 from $a(c) if c is uppercase but should be lowercase, and add 0 if c is already in the right case. Note that M's operator precedence is strictly left to right, so 2*f-1*x is unintuitively the same as (2*f-1)*x.

  • Finally, w s prints the now-alternating s.

Both lines have a leading space so that their first characters are interpreted as commands and not labels.


Vyxal r, 8 bytes


Try it Online!

The r flag shouldn't be needed, but bugs, bugs, bugs.


Convex, 16 bytes


Try it online!

Convex port of @Business Cat's answer.


Python 3, 95 bytes

Not nearly as golfed as @Rod's, but I'm posting it nevertheless.

lambda s:"".join([s[i],[s[i].lower(),s[i].upper()][i%2]][s[i].isalpha()]for i in range(len(s)))

Try it online!


J, 40 bytes


Try it online!

This follows almost directly from the definition of Composite Item (}):

We stack the upper and lowercase version of the input for our two possibilities using (tolower,:toupper).

Next we create a boolean list to indicate whether each character is alphabetic: e.&Alpha_j_ and take the scan sum of that: +/\@: which creates a monotonically increasing list which increases only on alphabetic characters. Finally we turn that into a boolean list where evens are 0 and odds are 1: 2|.

Putting those parts together means we alternate between the lower and uppercase versions of our input whenever we encounter a new alphabetic character, and only then.


C# (Visual C# Interactive Compiler), 84 bytes

int m,c;for(;(c=Read())>0;)Write((char)(c>64&c<91|c>96&c<123?m++%2>0?c|32:c&~32:c));

Try it online!

Modified version of The Lethal Coder's answer that takes advantage of some of the features of the interactive compiler.


Javascript, 104 bytes

I'm kind of new to this but wanted to submit anyway.


It takes in a string, splits it into an array so it can loop through with forEach and fit in as a one-liner, then goes through each character and index and adds the uppercase or lowercase version of the character depending on if the index is odd or not, then "or"s it with what I want to return (since otherwise it's undefined) and returns the second half of the string, so I don't have to clear the string to begin with or declare a new one.

However, this doesn't work with non-letter characters, so here's my pseudocode for something that would do that:

const sarcasticText = str=> {
    let newStr = '', numSkip = 0;
    for(let i=0; i<str.length; i++) {
        numSkip += str[i].match(/[a-z]/i) ? 0 : 1;
        newStr += (i + numSkip) % 2 ? str[i].toUpperCase() : str[i].toLowerCase();
    return newStr;

Basically, I'd implement a counter to check how many characters to offset.


SM83, 29 bytes

Input pointer in hl, output in de, trashes bc, a, flags.

06 55 2A 4F CB AF D6 41
38 0C FE 1A 30 08 CB A9
CB 08 38 02 CB E9 79 12
13 B7 20 E6 C9


    ld  b,$55       ;; 06 55    ; set b to alternating bits
    ld  a,(hl+)     ;; 2A       ; load char
    ld  c,a         ;; 4F       ; and into c
    res 5,a         ;; CB AF    ; turn a-z into A-Z
    sub 65          ;; D6 41    ; subtract 'A'
    jr  c,store     ;; 38 0C    ; if was less, not a letter
    cp  26          ;; FE 1A    ; compare to 26
    jr  nc,store    ;; 30 08    ; if not less, not a letter
    res 5,c         ;; CB A9    ; it is a letter; make uppercase
    rrc b           ;; CB 08    ; rotate b and check low bit
    jr  c,store     ;; 38 02    ; every other time skip next bit
    set 5,c         ;; CB E9    ; actually, make lowercase
    ld  a,c         ;; 79       ; store faster this way
    ld  (de),a      ;; 12       ; store
    inc de          ;; 13       ; and increment
    or  a           ;; B7       ; quick test against 0
    jr nz,loop      ;; 20 E6    ; if not 0 continue
    ret             ;; C9       ; else return

brev, 103 bytes

(define h(make-parameter #f))(over(if(char-alphabetic? x)((if(h(not(h)))char-upcase char-downcase)x)x))

Are the examples wrong? How do you get to InClUdE from AsCiI?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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