[Question]
  [
Write a program to replace all occurrences of "force" with "first" and all occurrences of "first" with "force", keeping the original case for all character positions:
```
"ForcefoRcefOrcE" -> "FirstfiRstfIrsT"
"FirstfiRstfIrsT" -> "ForcefoRcefOrcE"
```
The rest of the string must stay unchanged, and so running your program twice shall return the original string:
```
"thirst of forces" -> "thirst of firsts" -> "thirst of forces"
```
Your program should work on any initial string. So as a hint, you better avoid using magic characters as intermediate representation, because if you try a three pass replacement (`"force" -> "zzzzz", "first" -> "force", "zzzzz" -> "first"`), it will fail on strings containing `"zzzzz"`.
You should support the full range of characters allowed in a definition of a String by your programming language (in most cases, it's Unicode). Example, using JSON-style representation for non-printable characters (\u + 4 digits):
```
"\u0000\u0001\u0002\u0003the Force of the firsT"
                     |
                     V
"\u0000\u0001\u0002\u0003the First of the forcE"
```
  
[Answer]
## JavaScript (ES6), ~~93~~ 88 bytes
```
f=
s=>s.replace(/force|first/gi,s=>s.replace(/./g,c=>s[s.search(c)^1]||c,s="oicsetOICSET"))
```
```
<textarea oninput=o.textContent=f(this.value)></textarea><pre id=o>
```
Edit: Saved 5 bytes by optimising the unchanged letter case.
[Answer]
# [Retina](https://github.com/m-ender/retina), 33 bytes
```
iT`\OC\E\ocetsiTSI`Ro`first|force
```
[Try it online!](https://tio.run/nexus/retina#@58ZkhDj7xzjGpOfnFpSnBkS7JkQlJ@QlllUXFKTll@UnPr/v29ipUJJRqqCG4irkJSqUJ5ZkqFQmV8KAA "Retina – TIO Nexus")
Edit: Saved 5 bytes thanks to @MartinEnder for pointing out what `Ro` does.
[Answer]
# [Perl 5](https://www.perl.org/), 52 bytes
51 bytes of code + `-p` flag.
```
s%first|force%$&=~y/oceOCEistIST/istISToceOCE/r%eig
```
[Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@F@smpZZVFxSk5ZflJyqqqJmW1epn5@c6u/smllc4hkcog@hIEL6Raqpmen//4dkpCq45Rc5uyokJ@amKqRlBhWHAAA "Perl 5 – TIO Nexus")
Nothing too crazy going on. Find the occurrences of `force` and `first` non-case-sensitive (`s%force|first%%gi`), and then transliterates the characters to convert one to the other.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 61 bytes
Requires `⎕IO←0` which is default on many systems. Can be four *characters* shorter using the Unicode symbol `⍠` instead of `⎕OPT` .
```
(t←'force' 'first')⎕R{(m∊⎕A)c¨t⊃⍨~t⍳(c←819⌶)⊂m←⍵.Match}⎕OPT 1
```
[Try it online!](https://tio.run/nexus/apl-dyalog#U9Z71DfV0/9R2wSD/2lAUqMESKin5Rclp6orqKdlFhWXqGsClQRVa@Q@6ugCshw1kw@tKHnU1fyod0VdyaPezRrJQC0WhpaPerZpPupqygXyHvVu1fNNLEnOqAVq8A8IUTD8/z9NQd0NbCwXiAU2GMRKyw@CiqVlBsHE/IuSXSEsz6LiEBDL3NAUZIG6UkypARCASUMwaQQmjUsyUhXA5ivkpymAOCC3hygRrxfkIrheoEGuQL0A "APL (Dyalog Unicode) – TIO Nexus")
[Answer]
# PHP, 88 Bytes
[Online Versions](http://sandbox.onlinephpfunctions.com/code/7e93753dcfb53bde47d01c4cacfb3abaeaa1a1c6)
```
<?=preg_replace_callback("#first|force#i",function($t){return$t[0]^first^force;},$argn);
```
# PHP, 110 Bytes
```
<?=preg_replace_callback("#first|force#i",function($t){return strtr($t[0],iIsStToOcCeE,oOcCeEiIsStT);},$argn);
```
[Answer]
# Java 10, ~~318~~ ~~310~~ ~~284~~ ~~279~~ ~~277~~ ~~271~~ 256 bytes
```
String c(String s){var x=s.toLowerCase();int i=x.indexOf("force")+1,j=x.indexOf("first")+1,t=i>0&j>i|j<1?1:-1;var y=s.toCharArray();return-j<i?s.substring(0,i=t<0?j:i)+(y[i++]-=t*6)+y[i++]+(y[i++]+=t*16)+(y[i++]+=t*15)+c(s.length()>i?s.substring(i):""):s;}
```
-34 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##hZFNb8IwDIbv/AqrhylZR0U3jQOloAltEtIQUuHGOISSDnesmRKXUTF@O2vDh8SF5mDFzuvXyZNUbEQzXX4d4rUwBkYCs10DwJAgjOEwIY3ZJ8TstDF8txEatqHxSL2rX6kHwkjGA8wIMNx6mC3ldpwwJ1E6lg53/Yf0qozakC1TiL3WXdrDv7Tr9/1O0w8q68JaD1ZCv2gtitJaS8p11ky72DeeyRfGXoW1HjCkbqufdpC7rJih686bId23uXtMzkW3LPptfpU@czdmxlvL7JNWjPeurZF3HId3TLA/BI2Sxk@@WJc0TlA2CpfwXYI6QZnNQfAKGsCkMCS/PZWT91Me0TpjMXPejih4cEtz5HJTk6io1ifBqN5nrOPXOs1Qm2mN5iNvlctG38ZHG59oJcG@GVQCVVJ9ep3ZSBQXLcFCwi/SCgqV1/RNq56hntB5mCV5mTyOBq@Xk2E0mV4SFQ1qYNbcyrbuG/vDPw)
**Explanation:**
```
String c(String s){                     // Recursive method with String as both parameter and return-type
  var x=s.toLowerCase();                //  Temp String as lowercase of the input
  int i=x.indexOf("force")+1,           //  Index of "force" + 1 (becomes 0 if NOT present; >=1 if it is present)
      j=x.indexOf("first")+1,           //  Index of "first" + 1 (becomes 0 if NOT present; >=1 if it is present)
      t=i>0&j>i|j<1?1:-1;               //  Temp integer: -1 if "force" is found first; 1 if "first" is found first
  var y=s.toCharArray();                //  Convert the string to a character-array
  return-j<i?                           //  If either "force" or "first" is found:
    s.substring(0,i=t<0?j:i)            //   Return the substring before that (if any) + ('f' or 'F')
     +(y[i++]-=t*6)                     //   + 'i'↔'o' or 'I'↔'O'
     +y[i++]                            //   + 'r' or 'R'
     +(y[i++]+=t*16)                    //   + 's'↔'c' or 'S'↔'C'
     +(y[i++]+=t*15)                    //   + 't'↔'e' or 'T'↔'E'
     +c(s.length()>i?s.substring(i):"") //   + a recursive call for the rest of the input-String (if any)
   :                                    //  Else:
    s;}                                 //   Return the input-String as is
```
[Answer]
## CJam, 66 bytes
```
qY5m*_"force"{f{_eu}3/:z{~?}f%}:K~\"first"K.{[\]:P~@\/\f/P~@\f*\*}
```
Goes through every case variation of "first" and "force" and tries to split on it. If it can, it then joins it back with the reverse words.
Pseudocode:
```
input_chars = list(read_all_input()) # CJam: q
power = cartesian_power(2, 5) # CJam: Y4m*_
def case_variations(s): # CJam: {...}:K
    temp0 = [[i, j, upper(j)] for i, j in zip(power, s)] # CJam: f{_eu}3/
    temp1 = map(transpose, temp0) # CJam: :z
    ret = []
    for i in ret:
        for j in i: # CJam: {...}f%
            ret.append(j[1] if j[0] else j[2]) # CJam: ~?
    return ret
force_var = K("force") # CJam: "force"{...}:K~
first_var = K("first") # CJam: \"first"K
for force, first in zip(force_var, first_var): # CJam: .{...}
    current = [force, first] # CJam: [\]:P~
    input_chars = list_split(input_chars, force) # CJam: @\/
    input_chars = [list_split(i, first) for i in input_chars] # CJam: \f/
    input_chars = [list_join(i, force) for i in input_chars] # CJam: P~@\f*
    input_chars = list_split(input_chars, first) # CJam: \*
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*Is there is a way to use a reduce across slices of length 5 instead?*
```
®‘©ị“Ɓu“¡Ḣƭ»
Œlœṣ¢œṣ€¢j€¢j¢Œu⁸=ŒuT¤¦
```
**[Try it online!](https://tio.run/nexus/jelly#@39o3aOGGYdWPtzd/ahhzrHGUiB5aOHDHYuOrT20m@vopJyjkx/uXHxoEZh61LTm0KIsCAkUmlT6qHGHLZAKObTk0LL///8ruWUWFZcolGSkKqSBWWn5RcmpEDJFwc0/yNlVCQA)**
### How?
```
®‘©ị“Ɓu“¡Ḣƭ» - Link 1 helper that fetches the next word to use: no arguments
®            - recall value from register (initially zero)
 ‘           - increment
  ©          - place the result into the register
    “Ɓu“¡Ḣƭ» - literal dictionary compressed string list ["first","force"]
   ị         - index into (1-indexed and modular)
             - so this link first yields "first", then "force", then "first" and so on.
Œlœṣ¢œṣ€¢j€¢j¢Œu⁸=ŒuT¤¦ - Main link: list of characters, S
Œl                      - convert S to lower case
  œṣ                    - split on sublists equal to:
    ¢                   -   call the last link (1) as a nilad ("first")
     œṣ€                - split €ach on sublists equal to:
        ¢               -   call the last link (1) as a nilad ("force")
         j€             - join €ach with:
           ¢            -   call the last link (1) as a nilad ("first")
            j           - join with:
             ¢          -   call the last link (1) as a nilad ("force")
                      ¦ - apply a link to sparse indices:
              Œu        -   convert to upper case
                     ¤  -   nilad followed by link(s) as a nilad:
                ⁸       -     chain's left argument, S
                  Œu    -     convert to upper case
                 =      -     equal to S? (vectorises)
                    T   -     truthy indexes (indexes at which input is upper case)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 47 bytes
```
5W:qB!"o['first';'force']@!32*-cZ}_Zt5M_6MoZt|c
```
[Try it online!](https://tio.run/nexus/matl#@28ablXopKiUH62elllUXKJurZ6WX5Scqh7roGhspKWbHFUbH1Vi6htv5psfVVKT/P@/um9ipUJJRqqCG1Cdq0JSqkJ5ZkmGQmV@qUJ@HlgizRNokEJ@mgJQpToA "MATL – TIO Nexus")
This uses negative values as the intermediate step, and after the two passes it takes the absolute value.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~36~~ 35 bytes
```
K"first"srVjJ"force"mjKcdJcr0QKqVr1
```
[Try it online!](http://pyth.herokuapp.com/?code=K%22first%22srVjJ%22force%22mjKcdJcr0QKqVr1&input=%22The+fIrSt+of+the+First+of+the+fORCE+of+the+FIRST+of+the+FoRCe%22&debug=0)
Pyth is not especially good at string manipulations.
[Answer]
# Flex (lexer), 72 bytes
```
%%
 #define x(a) yytext[a]^=
(?i:first|force) x(1)6;x(3)16;x(4)17;ECHO;
```
To compile and run:
```
flex first.l
gcc lex.yy.c -lfl # -ll on Macs, apparently
./a.out
```
[Answer]
# Python 2, 171 bytes
I wanted to try to do this using built-ins, but it can't beat the messy method with all the splitting and zipping.
```
import re,string as g
def f(s):f="istISTECOeco";l=re.split("(first|force)",s,0,re.IGNORECASE);l[1::2]=[t.translate(g.maketrans(f,f[::-1]))for t in l[1::2]];print"".join(l)
```
I think it's pretty clear what I'm doing here. Split the string on instances of first and force (case-insensitive), replace those instances with versions translated using str.translate, and join it back into a string again.
[Try it online!](https://tio.run/nexus/python2#LY4xa8MwFIT3/oqHJglUE6ebjIcS3JIlgSSbY4Jw3nPVKpKRXsjS/@46pjd8cBx33ORuY0wMCXXm5MIANsPwckUCklkZqoXLvD2ems0e@ygqXycs8ugdSyHJpcy/FFOPSuisV3oOt5@7/aHZvB8bVfm2NGbd1S0XnGzI3jLKobjZH1y8JE2tMa9lp9Q8AwwuwH@pq8b5EAtRfEcXpFcTyWQfFxfGO0ulpvN9NWthuXC98I2/ED7ioUeIBE/zvHn6Aw "Python 2 – TIO Nexus")
[Answer]
# Python 2.7, ~~173~~ 165 bytes
8 bytes saved by quintopia
This one got gross:
```
lambda S:`[(t[0],t[0].upper())[t[1]]for t in zip("".join("first".join(s.replace("first","force")for s in S.lower().split("force"))),[l.isupper() for l in S])]`[2::5]
```
[Try it online](https://tio.run/nexus/python2#RY5NC8IwDIbv@xWhpxZKUcHLYEe9Cu5YCtatZZW6ljYy8M/PdijmkI@XPHmz2s7r533U0Lc3SVHuFK9JvGI0iTImUe6VsiEBgpvh7SIlRDyCmymxLmX8DlkkE70ezE/mpECDIayyubK98GGpR0WO3iH9LTDGpRcufy2hAn4DFFM3eWjbo1p76ECScyVsuJZ0ScOpmOBU3SBY2K5lwmHTRkBT9EFnA4vDKbwQTKkmwRLSSFTz/6ttoERMbkawNDNe9K4rbR3Y@gE)
Breaking it down step by step:
1. `S.lower().split("force")`: take the string, unify to lowercase, split into substrings separated by `"force"`
2. `s.replace("first","force")for s in <STEP 1>`: Replace all `"first"`'s with `"force"`
3. `_`.join("first".join(<STEP 2>)`[2::5]`_`: replace all `"force"`'s with `"first"` by recombining the `"force"` delineated substrings with `"first"` and rejoin into single string (underscores added to get tick marks correct)
4. `zip(<STEP 3>,[(2,1)[l.isupper()]for l in S])`: zip each character of replaced phrase with case encoding of original string (2 for lowercase, 1 for uppercase)
5. `_`[(t[0],t[0].upper())[t[1]==1]for t in <STEP 4>]`[2::5]`_`: Restore original casing, converts list to string (underscores added to get tick marks correct)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~201~~ ~~183~~ ~~226~~ 214 bytes
Had some bugs...
Still needs to be golfed down quite a lot
(saved 12 thanks to ceilingcat)
```
char*s,*p,*q;main(i,v)char**v;{puts(s=v[1]);do{p=strcasestr(s,"first");q=strcasestr(s,"force");if(p&&(!q|p<q))p[1]+=6,p[3]-=16,p[4]-=15;else if(q)q[1]-=6,q[3]+=16,q[4]+=15;s=p&&(!q|p<q)?p:q;}while(s++);puts(v[1]);}
```
[Try it online!](https://tio.run/nexus/c-clang#XY6xTwMhHIX/FbyhgYMbatVBSjp5iYNL7WKaDoickFwL3I9eY2r/bFcRzsU4vZeXLy9fUkYONbDaszrwvbQHbNlIprUe@dkfI2AQ43a@I/zNnb2AOCgJOgcGVnV2gFgRHv7vblA677bDfjbDV@HTLwMhPv9Qccf8drFrxLyUm1Juue5Bo0wHEjLTZCZkhhYmZIYWBsSfr5W/D/xyMrbXGCglfFL9Fb2klKon@YGi0ah1a6XRq0YnGw16cUfkOtRm7w2SERXRh/Zx/byZqobqW3W9fIfU7BfXXwfXKKmM/gE "C (clang) – TIO Nexus")
[Answer]
# C# 273 bytes
```
string c(string s){var x=s.ToLower();int i=x.IndexOf("force")+1,j=x.IndexOf("first")+1,t=i>0&j>i?0:j>0?1:0;return i>0|j>0?s.Substring(0,t>0?(i=j):i)+(char)(s[i++]-(t>0?-6:6))+s[i++]+(char)(s[i++]+(t>0?-16:16))+(char)(s[i++]+(t>0?-15:15))+c(s.Length>i?s.Substring(i):""):s;}
```
[Try it online!](https://tio.run/nexus/cs-mono#jVJNi8IwEL37K4YeloRqaXfRQ0v1IC4UFKEV9uB6qDW1U9xmSVI/cP3tbj@0rLBgcxgy772ZTF4S7UIpYXbuAEgVKozgKpXAbAsRuW0kPe9DAUdXGgs@5QcmCHUwU4Du0fCyDTvOY6LFXERMo7rVTR9gFFJVsHJxaL6kQxyZdjo0R5ZtOoKpXGRQED8lJI0gX9enErOrCoSgm1IbqU6iJBSUyCXq@qpHSq43sAeU6jX0KNBrgTWwrVLyL9e3rX7BFdc0pizbqqSY7O8ASG1No7Z0LleA73y9K7y5WbTnuIFZiNnNouUKQlpaCBCcpGJfxphnku@Y8SFQsSlmjEREe68tos5zZe1aC2XM/ZY9Y/Tb9pyLaNJO6Qm5aKX8zM1iVdGq4msV31TCoPIFeAxlUn6Ydi1n4ampULBmcECVwInnbaqf1Lc4flGWeiJQ98mrR2uuMffHk4bx/GDRJNwf31/s0rlcfwE "C# (Mono) – TIO Nexus")
Direct port of [Kevin Cruijssen's Java answer](https://codegolf.stackexchange.com/a/118234/44998), turns out when it comes to getting the char in a string at a given index, C# is much golfier than java (`s[i++]` instead of `s.charAt(i++)`)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 41 bytes
```
r"first|force"_d"i1o s1c t1e"¸m²®+ZuÃq}'i
```
[Try it online!](https://tio.run/nexus/japt#@1@klJZZVFxSk5ZflJyqFJ@ilGmYr1BsmKxQYpiqdGhH7qFNh9ZpR5Uebi6sVc/8/1@pJCNVwQ2kViE/TQHEAWkPUQIA "Japt – TIO Nexus")
This would be considerably shorter if Japt had a sane transliterate function...
Alternate version:
```
r"first|force"_d"io sc te"¸®¬¸²Ã®+ZuÃq}'i
```
[Try it online!](https://tio.run/nexus/japt#@1@klJZZVFxSk5ZflJyqFJ@ilJmvUJysUJKqdGjHoXWH1gDJTYebD63Tjio93FxYq575/79SSUaqghtIvUJ@mgKIAzIiRAkA "Japt – TIO Nexus")
[Answer]
# C#, 235 chars
```
string a(string s){var l=s.ToLower();int f=l.IndexOf("first"),F=l.IndexOf("force"),m=f<F&f>-1?f:F>-1?F:f;return ++m>0?s.Substring(0,m)+(char)(s[m]^6)+s[m+1]+(char)(s[m+2]^16)+(char)(s[m+3]^17)+(s.Length-m>5?c(s.Substring(m+4)):""):s;}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 55 bytes
```
gsub(/first|force/i){$&.tr(s="iIsStTEeCcOo",s.reverse)}
```
[Try it online!](https://tio.run/nexus/ruby#U1YsKk2qVNAt@J9eXJqkoZ@WWVRcUpOWX5Scqp@pWa2ipldSpFFsq5TpWRxcEuKa6pzsn6@kU6xXlFqWWlScqln7/z9YsUJJRqqCm2dQcIiCG4jvllkUXKIANA1onAJQhbMrAA "Ruby – TIO Nexus")
[Answer]
# Java, 382 bytes *non-comptent*
[**Try Online**](http://ideone.com/agFhBI)
```
String f(String t){String s="";for(String w:t.split(" "))if(w.equalsIgnoreCase("force")|w.equalsIgnoreCase("first"))s+=" "+w.charAt(0)+(char)(w.charAt(1)+(w.charAt(1)=='o'|w.charAt(1)=='O'?-6:6))+w.charAt(2)+(char)(w.charAt(3)+(w.charAt(3)=='c'|w.charAt(3)=='C'?16:-16))+(char)(w.charAt(4)+(w.charAt(4)=='e'|w.charAt(4)=='E'?15:-15));else s+=" "+w;return s.substring(1,s.length());}
```
[Answer]
**C# (269 Bytes)**
```
string s(string z){var u=z.ToUpper();var a=new[]{"FIRST","FORCE"};return String.Join("",u.Split(a,StringSplitOptions.None).Aggregate((c,n)=>c+(u.Substring(c.Length,5)==a[0]?a[1]:a[0])+n).Select((c,i)=>Char.IsLower(z[i])?Char.ToLower(c):c));}
```
yet another c# solution, only the second-smallest because I declared two variables and so can't use lambda syntax. oh well, I had fun. :)
explanation: 
* upshift the original string, then split on "FORCE" and "FIRST".
* aggregate
the results and on every split, find the five-character substring that was used to split the original string using the length so far of the string being
aggregated. if it was "force" make it "first" and vice versa
* select all the characters of the newly created all caps string and
check if the original string was lowercase at the same index. if yes, return lowercased character at that index in the new string, otherwise return the uppercase character
]