[Question]
  [
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](https://en.wikipedia.org/wiki/ASCII#Printable_characters), 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 [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), standard loopholes apply and the shortest answer in bytes wins!
  
[Answer]
## 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"))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 8 bytes
### Code:
```
lvyJ¤aiš
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@59TVul1aEli5tGF///7uDqGucbnVsYXV@Ym5ecUKysqq8Wpxjv6@Pu5KioqAgA "05AB1E – TIO Nexus")
### 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
```
[Answer]
# 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](https://tio.run/nexus/sed#fYvRCoIwGEbv9xQbUlSgonQZhYlFICUV3WjJspGj2WT/xOrhWwZdd/WdA@cz4A5Sar@Ow0F6@u7ImQ3drMm8TGS@e@XGBLtwtUJjH1n8XojmwvCES9CK0WqK4ig4RHn1zOFZnaUAi1j9Uy8P4s06IoSgJAmXeCuLG3SGF1Lh7ideDtqXHDB70KoWDLdcCAyaKt2hLrGQLVMFBfY/a@r6lwXe3H/LWnN5B2OrDw).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
nŒsTm2
ŒlŒuÇ¦
```
[Try it online!](https://tio.run/nexus/jelly#@593dFJxSK4R19FJOUcnlR5uP7Ts/8PdWw63P2paE/n/v2Ows6cnl4kRl3JmXnJOaUqqgk1mfnFJUWpirh1XQICzu0JQfnJ2saKiooJbfpECUDynSo/Lx9UxzDU@tzK@uDI3KT@nWFlRWS1ONd7Rx9/PFaiUKyQjs1ghtSIxtyAnVaE8MydHobgksagEyCzJUCgtKEgtSk4sTgUA "Jelly – TIO Nexus")
### 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.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~16~~ 14 bytes
```
r"%l"_m"uv"gT°
```
[Try it online!](https://tio.run/nexus/japt#@1@kpJqjFJ@rVFqmlB5yaMP//0qOwc6enkoA)
### 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
```
[Answer]
# [Python 3](https://docs.python.org/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!](https://tio.run/nexus/python3#DcJBCoAgEAXQfadwOdNComXhSaIg0PDDoGITeXvr8Xpz03DlamCQ/uVR4qVUJKWQvKN5BFuFSiDe2s5rOxws7lNKPIl7j0EkmzdX8R8 "Python 3 – TIO Nexus") or [Try all test cases](https://tio.run/nexus/python3#hZBPa8JAEMXvfooJwe5ukVCkJ20KQaII0kotvYiGbbIhQzfZZWfF2C@fbmjvvQzz5/0evBkqVUPNSSwm0KcPE6iNAwTsgBbWYee56qqUz@9RJB69Vlwc@5NY9ucUEySpbSO5GEaKRurIssNqu2Uz9jgPJcau1JdKwRMa8k7J9jlsd3n2kRftraBb@2k0xVF8d54W2e71JY@iKCj2@9UG3kz5RWGGdXAPrP5Owum9QQLVy9ZqBVfUGshL50PrG9DmqlwpSf0nvFj7JzyF5OMDlr9xGRPDDw "Python 3 – TIO Nexus")
[Answer]
# [Alice](https://github.com/m-ender/alice), 18 bytes
```
/olZlYuN
@iy.u..//
```
[Try it online!](https://tio.run/nexus/alice#@6@fnxOVE1nqx@WQWalXqqenr///v0dqTk6@Qnl@UU6KIgA "Alice – TIO Nexus")
### 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.
[Answer]
# 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!](https://tio.run/nexus/ruby#fYtPC4IwHEDv@xQTTSzIyuoQVGBhEUhJRadITEeOphv7TfrrV888dO72HrxXXaA4W52jePllp/myDNPmMjFHw3ffaRn2adJr2nEqy6pyd/PVCg0cpNM8ZkVC8JhyUJJE2RT5nnvwwuwRwiM7cwa6ppunRuj6m7WnaRoKgvkSb3l8hdrwgktcf@xpo31KAZN7lAlG8I0yhkFFUtWoUsz4jcg4AvI/K4T4ZW5v5ny4UJTnULVF9ws "Ruby – TIO Nexus")
Thanks to Ventero for amazing input -- check the comments for details.
[Answer]
# [C (tcc)](http://savannah.nongnu.org/projects/tinycc), ~~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!](https://tio.run/nexus/c-tcc#bU5da8IwFH3vr0gtSpKywWQ@bKmOTrohyBQHPlqy2NKym0ZylaGuP9vnWn0RIffhwD1fnAZETlUhLUd2zI2lguOwRAmbQtKWe@PYexn8hyF0@1E0eOUoMAyZqBsty4oy7@iR9i4NhBMtrt8VcqqHnSIDMOTPWFh3mNjstkg1Ezc9/h5PJk7lue@kg7JSsFtnJCoNbm0m9cjpmybxMkn1PsW9/jGAgR/0Vt00ns6@Et/3nZn5fPxJFkb9YusgH8aSth8Oj@7lT@93C2uvOVXmQUlVZGc "C (tcc) – TIO Nexus")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes
```
Xktkyy-f2L))5M(
```
[Try it online!](https://tio.run/nexus/matl#@x@RXZJdWambZuSjqWnqq/H/v3pGak5OvkJ5flFOijoA) Or [verify all test cases](https://tio.run/nexus/matl#hYtNC4IwHMbvfYr/kFoeCpK6RWBmIdgLJdEpW7ZwuDXZJra@vO3UtcvD8/J7bt2lMpW1o2eQ@v5sO@xWWYfDU5QkuIengROPvQrePCjMmdRGUSIWrk3j8Bznwubairvk2kPe4NrPw3S/ixFCjjgcog0cZVFpl2EtFbgv/4zdlJVMA30TUXMKLeMctCHKOGtK4LKlqiCa/gObuv6B4WQZ4C8).
### 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
```
'
[Answer]
# 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.](https://tio.run/nexus/java-openjdk#lZFRT8IwFIXf@RV3I5AtxMUNQoJjI5OgIUEkYnwxSkop0ti1pO3ECfOvY4c86sNebk5ve79z2mKGlII7RPm@BkC5JnKNMIFpuQSYa0n5G2AHb5B8fgHkhqZf1ExRGmmKYQocIjiii3h/Piwj2w4NCWh0Ga6FdEqNr5ArW9GJ4zo47naauN/zDzjudY3yg/aAtlqNoO8P8KEdXOHmd1ndUBKdSQ4yLI5habvNlszYnt0/BF1BatI7v@aniOfoudIk9USmva3Z0ow73MOOncyH47HtaTE0URIpUe647ula/890gooDdcoxy1YE@lQoLQlK44qEySh5Gi3SfKHydCmYqlv15mtjkUzupyPLsirSZrPhLTwI/K7MLNwICSYT@/IqYh43VAH5ROmWEdhRxsp/kNpIvQEmdkRipEhFaOJf//28Ra04/gA)
```
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
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 25 bytes
```
{ḷ|ụ}ᵐ.{ḷ∈Ạ&}ˢ¬{s₂{∈Ạ}ᵐ}∧
```
[Try it online!](https://tio.run/nexus/brachylog2#@1/9cMf2moe7l9Y@3DpBD8R51NHxcNcCtdrTiw6tqS5@1NRUDREBKah91LH8/3@ljNScnHyF8vyinBSl/1EA "Brachylog – TIO Nexus")
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
```
[Answer]
# Pyth, 11 bytes
```
srR~xZ}dGrZ
```
[Try it here](https://pyth.herokuapp.com/?code=srR~xZ%7DdGrZ&test_suite=1&test_suite_input=%27ASCII%27%0A%2742%27%0A%27%23include+%3Ciostream%3E%27%0A%27LEAVE_my_symbols%23%21%23%26%5E%25_ALONE%21%21%21%27%0A%27PPCG+Rocks%21%21%21+For+realz.%27%0A%27This+example+will+start+with+lowercase%27%0A%27This+example+will+start+with+uppercase%27%0A%27A1B2%27&debug=0)
### 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
```
[Answer]
# [Perl 6](https://perl6.org), ~~32~~ 30 bytes
```
{S:g/<:L><-:L>*<:L>?/$/.tclc()/}
```
[Try it](https://tio.run/nexus/perl6#jZFdS8MwFIbv8yvOmLpOtxaHeLGPalaqFKorW6dMhqNmcQumbWjSfSj@Mu/8YzMdKgiKOxfhnJznPTm8ySWFxalJWihewwFJpxQ6m5dBc2a1m77druvjsMjOrD3LVIQTo2q9bjR7rqhU0AHOEiqN6vubKQVnyqjU7UpRqYzFLZTr8aEGW0jwKIGjraqFHtPsc0DdBmPMEpGrGozpSlCi6LQKLwiASSj2Mbbdag2@ujXY3piCZhy9bvDA8Tz4P/RLgKXDPHTSgJ2iUJw0UJklhOfamDZLpcpoFNt/4mUvcfhw6mq2J8PMja5s5Lv4xp3E64lcxw8pl@VS@eB@f4L93rVbKpV@6H2KF5odTeQo7qb@N8t7ScGiIHAuoZ@SJ1koL7SNeh/@bP62SyCcmWadp0HBPvYy6FPM70wUzrW1dBXFglNYMs5BqihTOlVzyIX2lUT637ZDwrknwV3hOOAuLD3ugwyjvoJbFs5hKALaJ1i6CB93G7taio8fGh8 "Perl 6 – TIO Nexus")
```
{S:g{<:L><-:L>*<:L>?}=$/.tclc}
```
[Try it](https://tio.run/nexus/perl6#jZHfSsMwFMbv8xRnTF2nW8UhXritmpUqhepKV5XJcNQsurC0DU26P449mXe@2EyLCoKi5yKck/P7Tg5fcklhfmKSNopXsEfSCYXudj04fV53Tj2r09THfpGdbbo7h6YinGy2mjxXVCroAmcJlUb97dWUgjNl1JpWrahUxuI2yvXwUINtJHiUwEGpaqOnNPsY0LTAGLFE5KoBI7oUlCg6qcMaATAJxTZG2a034LPbgPLGFDTjaLPFA9t14e/QLwGWNnPRcQv@FYXiuIWqLCE817Z0WCpVRqPY@hWvuonNbyaOZvsyzJzoykKeg2@dcbway1X8mHJZrVT3HnbH2OtfO5VK5Zveo3iu2eFYDuNe6n2xvJ8ULPJ9@xKClMxkobzQNup9@Iv50y6@sJ81a88GBfvUzyCgmN@bKJxqa@kyigWnsGCcg1RRpnSqppAL7SuJ9L@VQ8KpK8FZ4tjnDixc7oEMo0DBHQuncCN8GhAsHYSPeq3/WoqPHlvv "Perl 6 – TIO Nexus")
## 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
}
```
[Answer]
# 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
```
[Answer]
# 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()
  }
}
  
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~17~~, 13 bytes
```
VUÍáƒ¨áü$©/ì&
```
[Try it online!](https://tio.run/nexus/v#ATcAyP//VlXDjcOhwoPCqMOhw7wkwqkvw6wm//9MRUFWRV9teV9zeW1ib2xzIyEjJl4lX0FMT05FISEh "V – TIO Nexus")
Or [Verify all test cases!](https://tio.run/nexus/v#@x/mHnq49/DCQ82HVhxeeHiPyqGV@ofXqP3/7xjs7OnJZWLEpZyZl5xTmpKqYJOZX1xSlJqYa8fl4@oY5hqfWxlfXJmblJ9TrKyorBanGu/o4@/nqqioyBUQ4OyuEJSfnF0M5Cm45RcpAPXlVOlxhWRkFiukViTmFuSkKpRn5uQoFJckFpUAmSUZCjn55alFyYnFqfiVlRYUQJU5GjoZAQA)
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/á
```
[Answer]
# PHP, 71 Bytes
```
for(;a&$c=$argn[$i++];)echo ctype_alpha($c)?(ul[$k++&1].cfirst)($c):$c;
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVfJIzcnJ11EIzy/KSVFUsv6fll@kYZ2oppJsC1YQrZKprR1rrZmanJGvkFxSWZAan5hTkJGooZKsaa9RmhOtkq2trWYYq5eclllUXKIJErdSSbb@/x8A "PHP – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~26~~ 24 bytes
```
qeu{_'[,65>&,T^:T{el}&}%
```
[Try it online!](https://tio.run/nexus/cjam#@1@YWlodrx6tY2Zqp6YTEmcVUp2aU6tWq/r/f0hGZrFCakVibkFOqkJ5Zk6OQnFJYlEJkFmSoZCTX55alJxYnAoA "CJam – TIO Nexus")
### 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)
```
[Answer]
**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.
[Answer]
# [Retina](https://github.com/m-ender/retina), 32 bytes
```
T`l`L
01T`L`l`[A-Z][^A-Z]*[A-Z]?
```
[Try it online!](https://tio.run/nexus/retina#fYtBC4IwAEbv@xUbUoegSOkYxRILYZSUdEhSlw0cbU22idWftxWdu3y8D97r01KUBEz9tCSOMjw@nbP8s6MvL/seH8I4BrMAePxeifbK4JwrYzWjcgFIhI9RIZ@FecqLEsZD3jAfFJjsthFCCCRJuIF7Vd2Me3CtNHSdeE1AWnMD2YPKRjDYcSGgsVRbh7aGQnVMV9Sw/1rbND8N@6vgDQ "Retina – TIO Nexus")
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.
[Answer]
## 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()
        }
    })
```
[Answer]
# 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!](https://tio.run/nexus/haskell#bYqxCoMwFAB3vyKaDgptaaRTaARrF8FNOpVSgiY0oCY8nzSC/26XDh288e5W0zsLSG4S5bF4Swg0jT2fk8WMlUJUQLyIH2jvzinYo63sR8EzDHXiecwOOqHzwrKT8FzTOXjRTnRrL80gWkvchDVCNewYjfK6KMsoID/@0znd9tQMTTe1ilyMHRGU7LPtMWfXNFq/ "Haskell – TIO Nexus")
~~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!
[Answer]
# [Perl 5](https://www.perl.org/), 24 bytes
**23 bytes + 1 byte for `-p`.**
Thanks to [@Dada](https://codegolf.stackexchange.com/users/55508/dada) for -2 bytes.
```
s/\pl/--$|?uc$&:lc$&/eg
```
[Try it online!](https://tio.run/##fYvNCoJAFEb3PsWI1s6soE2/mFgIUlLRKhKzIYeuzjB3xAyfvclF6zYf58D5BJUw0Xa7GM40uhcBruPY7arK7P4UunHpQ2vv6IehYbEyg@pOyZxxVJKmxdKIAu8cJEWTYFPcOKBlWv1rL/Gi/S4wTdOIY39LDjx7YmdkwyXpfvAeGKecIaGvtBBASc0ACKpUqg5VToDXVGYp0v9ZJcQv80br8YcLxXiJ2hFf "Perl 5 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 17 bytes
```
s/\pL/<`>|uc$&/ge
```
[Try it online!](https://tio.run/##fYtBC4IwGIbv@xXfWHkrSeomgomFICUVnSKzNVLa2tgmZvTfbYfOnd7ngedVTPPFQLByCxM1GP@kcj@8RJ@Wjjz/zoYh3idZhuYBIs2T8vbGIGyksZpVIkJ5Gh/TUvSl6cVVckMw8c7jMs63mxRjjIoiWcNO0odxBiupwf34e4oOdWOAvSqhOIOu4RyMrbR1aGvgsmOaVob9z1qlflk8WwbwBQ "Perl 5 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 46 bytes
```
T`L`l
T`l`L`.(?=([^a-z]*|[a-z][^a-z]*[a-z])*$)
```
[Try it online!](https://tio.run/nexus/retina#fYvNCoJAGEX38xQzWJFCQtKyH0wsBCkpaSOpkw049NmIo5jSu5uF61bnHji382M3BuTH0FOfblbTIKSz9qq9gy8G@W1VG6ldZ54tx0ELAyn8mUB1Z3jJhSwLRrM1cm3zYkdZE8kmuwmQClEm4Tgy3ePBJoQgz7P2@CSSh@wN70SB@x@0OvJTLjF70SwHhmsOgGVJi7KfZYpB1KxIqGT/syrPh8ycb40P "Retina – TIO Nexus") Includes test cases.
[Answer]
# PHP 5, 54 bytes
```
<?=preg_filter('/\pL/e','($0|" ")^a^aA[$i^=1]',$argn);
```
[Answer]
# 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;};
```
[Answer]
# Groovy, 79 bytes
```
{x=0;it.toUpperCase().collect{(it==~/\w/)?x++%2?it:it.toLowerCase():it}.join()}
```
[Answer]
# [Python 3](https://docs.python.org/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!](https://tio.run/nexus/python3#ZZDNDoIwDMfvPkXDqYsJiR6J@CKEA0qBJliWFXBvj5OBidrD@pHfv1271NSAmwRNdoBgPu9ZR2Sx04jGrDXNi3INmsEBAwv44pRl5zJKQNPKWpIaOfLgU0ePYaa9oCGfySlhzJ8d9wQ9CXpzeTvdpgfl1ipJ/tHrF6q/6Od3rpKWMGp22jqWEQOe@4LLo4bHLOveS3W7hyO0Hb8A)
]