| Bytes | Lang | Time | Link |
|---|---|---|---|
| 012 | Haskell + hgl | 240223T174129Z | Wheat Wi |
| 129 | Rust | 240509T083518Z | 138 Aspe |
| 099 | YASEPL | 240223T183030Z | madeforl |
| 048 | R | 240327T084704Z | Patric |
| 043 | Scala 3 | 240227T084150Z | t9dupuy |
| 078 | Scala 3 | 240310T130535Z | 138 Aspe |
| 179 | Pascal | 240225T165456Z | Kai Burg |
| 041 | Labyrinth | 240227T053314Z | Bubbler |
| 055 | Rattle | 240227T024422Z | Daniel H |
| 056 | JavaScript ES6 | 240222T190205Z | Arnauld |
| 008 | Brachylog | 240226T142433Z | Fatalize |
| 024 | K ngn/k | 240222T223848Z | ovs |
| 011 | Bash | 240224T142456Z | vengy |
| 107 | Lua | 240225T112524Z | Ed The & |
| 007 | Japt v2.0a0 | 240223T220422Z | Shaggy |
| 064 | Java 10 | 240223T151133Z | Kevin Cr |
| 071 | Excel | 240223T141838Z | Engineer |
| 016 | Bash + coreutils | 240223T140011Z | qwr |
| 042 | APL+WIN | 240223T090454Z | Graham |
| 002 | V vim | 240223T082935Z | tsh |
| 007 | MathGolf | 240223T082846Z | Kevin Cr |
| 001 | 05AB1E legacy / 2sable | 240223T082149Z | Kevin Cr |
| 058 | Haskell | 240223T044422Z | totallyh |
| 031 | R | 240223T071356Z | pajonk |
| 020 | K ngn/k | 240223T065533Z | Bubbler |
| 012 | APL Dyalog APL | 240223T033154Z | Mukundan |
| 014 | J | 240222T202814Z | Jonah |
| 014 | Perl 5 p | 240222T223749Z | Xcali |
| 142 | Go | 240222T223111Z | bigyihsu |
| 042 | PowerShell Core | 240222T210912Z | Julian |
| 009 | Japt v2.0a0 | 240222T211209Z | noodle p |
| 141 | TypeScript’s type system | 240222T205318Z | noodle p |
| 010 | Charcoal | 240222T202809Z | Neil |
| 007 | Retina 0.8.2 | 240222T202408Z | Neil |
| 040 | C gcc | 240222T191608Z | Mukundan |
| 001 | Uiua SBCS | 240222T192013Z | chunes |
| 059 | Acc!! | 240222T184515Z | DLosc |
| 047 | Python 3 | 240222T184058Z | Larry Ba |
| 012 | Python | 240222T182132Z | Mukundan |
| 002 | MATL | 240222T183556Z | Luis Men |
| 001 | Vyxal 3 | 240222T182232Z | Larry Ba |
Haskell + hgl, 16, 12 bytes
m$TL?.TU~<iU
Thanks to Bubbler's comment on a different post for helping me realize how to take 4 bytes off
Explanation
This is really simple. m maps across a string iU checks if a character is uppercase, TU makes a character uppercase TL makes it lowercase.
Using parsers, 22 bytes
gk$my$(TL<pU)#|(TU<hd)
Using regex, 38 bytes
skX$nt$ozW(:)(Β<>β)$K '{'<Fk"_|"<Alf
This builds the regex
A{a_|B{b_|C{c_|D{d_|E{e_|F{f_|G{g_|H{h_|I{i_|J{j_|K{k_|L{l_|M{m_|N{n_|O{o_|P{p_|Q{q_|R{r_|S{s_|T{t_|U{u_|V{v_|W{w_|X{x_|Y{y_|Z{z_|a{A_|b{B_|c{C_|d{D_|e{E_|f{F_|g{G_|h{H_|i{I_|j{J_|k{K_|l{L_|m{M_|n{N_|o{O_|p{P_|q{Q_|r{R_|s{S_|t{T_|u{U_|v{V_|w{W_|x{X_|y{Y_|z{Z_
In hgl's regex flavor A{a_ matches an A but returns it as a. So this does this for every letter uppercase and lowercase.
Reflection
It's really weird that the main answer uses basically no function composition, and the only infix function it uses is function application, especially considering it uses 6 functions in total. However the I golfed away the l3 is still glue, and is clearly costing more than it should.l3 now, which is good.
The parser version is never going to be competitive for this challenge, but I did it anyway to get practice with that part of the library. 22 bytes is not awful, I don't think, but it could probably be improved.
Although the regex usually beats the parser when it is possible to write a regex, for this specific task the regex answer is even less likely to be competitive than the parser. It is fun to build the regex from components rather than
- A case swap builtin would probably be good. It seems weird and niche, but I can see how this is can actually be useful in odd ways, and apparently both Vyxal and Python have it as builtins.
l3 iFis probably worth having, plus a version that only lifts over the first two arguments.l3could have an infix version. Even at 3 bytes, this would save bytes.- The
trfunction that I see other people using seems like it could be helpful in general, although it's unlikely it would ever be the way to go for this answer. Best case scenario is 15 bytes. - Maybe something that combines
gkandgMywould be useful. "Apply this parser as many times as it takes to finish the string". - A shortcut for
fm hd, parse a character and apply a function, would probably be good. - I could use a version of transpose that truncates the extra lines. With this I could build the regex doing:
ic"|"$txk[Β<>β,cy"{",Alf,cy"_"] - A shortcut for
zW KorzW(:)would be useful.
Rust, 129 bytes
129 bytes, it can be golfed more.
Golfed version. Attempt This Online!
|x:&str|->String{x.chars().map(|c|if c.is_uppercase(){c.to_lowercase().to_string()}else{c.to_uppercase().to_string()}).collect()}
Ungolfed version. Attempt This Online!
fn swapcase(input: &str) -> String {
input
.chars()
.map(|c| {
if c.is_uppercase() {
c.to_lowercase().to_string()
} else {
c.to_uppercase().to_string()
}
})
.collect()
}
fn main() {
assert_eq!(swapcase("abc"), "ABC");
assert_eq!(swapcase("ABC"), "abc");
assert_eq!(swapcase("Mixed Case"), "mIXED cASE");
assert_eq!(swapcase("1234"), "1234");
assert_eq!(swapcase("123#$%hIjK456"), "123#$%HiJk456");
println!("All tests passed.");
}
YASEPL, 99 bytes
=f=1'=l®1=i`1=s¥i,1=w$32=j$65=m$91`2!$j»}3,s,4!j+}2,m,2!)s!m}3,123,3+w!j+6!w-64|2`4$j+w»`3!~!i+}2,l
explanation:
=f=1'=l®1=i`1=s¥i,1=w$32=j$65=m$91`2!$j»}3,s,4!j+}2,m,2!)s!m}3,123,3+w!j+6!w-64|2`4$j+w»`3!~!i+}2,l packed
=f declare F (character that gets printed)
=1' get input from user, set result to var1
=l®1 declare L (length of var1)
=i declare I (increment variable)
`1 !i }2,l while I < L ...
=s¥i,1 set S as var1[i]
=w$32 set W as 32 (switcher)
=j$65 set J as 65 (second increment variable)
=m$91 set M as 91 (max)
`2 !j }2,m,2 while J < M...
!$j» set F to char(J)
}3,s,4 `4 if F == S...
$j+w» break out of loop, set F to char(J+W)
`3!~ print F, and continue
+ else, add 1 to j and loop.
!)s set F to S
!m}3,123,3 `3 if M == 123...
!~ print F, and continue
+w else... / add W to M
!j+6 add 6 to J
!w-64 subtract 64 from W (making it negative)
|2 go back to point 2
+ once all done, add 1 to I and loop
R, 48 bytes
\(s)gsub("([A-Z]*)([a-z]*)","\\L\\1\\U\\2",s,,T)
(T for perl=TRUE)
Scala 3, 52 bytes 43 bytes
_.map(c=>if(c>'Z')c.toUpper else c.toLower)
-5 bytes thanks to @movatica
-4 bytes thanks to @Bubbler
Scala 3, 78 bytes
78 bytes, it can be golfed more.
_.map{case c if c.isUpper=>c.toLower;case c if c.isLower=>c.toUpper;case c=>c}
Pascal, 179 B
This is a full program requiring a processor supporting ISO standard 10206 “Extended Pascal” (in particular the index function).
Furthermore the implementation must provide uppercase and lowercase characters.
program p(input,output);const
A='ABCDEFGHIJKLMNOPQRSTUVWXYZ';B='abcdefghijklmnopqrstuvwxyz';var
C:char;begin while not EOLn do begin
read(C);write((C+B+A)[index(A+B,C)+1])end end.
Ungolfed:
program swapCase(input, output);
const
modernLatinAlphabetMajuscule = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
modernLatinAlphabetMinuscule = 'abcdefghijklmnopqrstuvwxyz';
var
buffer: char;
begin
while not EOLn(input) do
begin
{ This is equivalent to `buffer ≔ input↑; get(input)`. }
read(input, buffer);
{ The `+` operater concatenates string and character values. }
write(
output,
(
{ If `index` (below) returns zero
(meaning pattern not found)
the value of `buffer` is used. }
buffer
+ modernLatinAlphabetMinuscule
+ modernLatinAlphabetMajuscule
)[
{ The `index` function returns the index of
the pattern (second parameter)
in the sample (first parameter). }
index(
modernLatinAlphabetMajuscule
+ modernLatinAlphabetMinuscule,
buffer
{ In Pascal `string` indices are 1‑based. }
) + 1
]
)
end
end.
Note, the program does not work correctly if input is empty since there is no EOF test.
Labyrinth, 41 bytes
" @
,::4/*_
. _6 "
$* %23
326#(
_ /
%#)
Labyrinth doesn't have any built-ins related to letter case, and making multiple if-branches is incredibly wacky. Fortunately, it can be worked around using arithmetic operations. It also helps that it has the XOR operator, which means it suffices to identify letters vs. non-letters and apply XOR 32.
The code is kinda obfuscated by the use of "stack height" which saves 1 over pushing the first digit literally (_ push 0 and then append a digit). Unobfuscated, the code does the following:
Big loop:
,:: getchar(x), dup twice [x x x]
exit (turn left) on EOF(-1), continue (turn right) otherwise(positive)
_64/* [x x2] make chars 63 or below into 0 -> x2
_32% [x x3] modulo 32 -> x3 (letter iff 1 <= x3 <= 26)
(_26/ [x x4] decrement and divide by 26 -> x4 (letter iff x4 == 0)
)_2% [x b] increment and modulo 2 -> b (0 or 1, 1 means letter)
_32*$ [x'] x XOR 32 if letter, x otherwise
. [] putchar
Rattle, 55 bytes
|!II^P[gnsF0*32+~,>]`:sF2$F1-~:s<91[1g>64]:s<123[1g>96]
By design, Rattle does not have many built-ins to encourage more creative problem-solving. This means there is no built-in for checking or changing character case whatsoever. With the current number of bytes, this Rattle code is able to 1) iterate over all characters, 2) check if the character is upper-case or lower-case (implemented from scratch), and 3) swap the character case if this criteria is met.
This code is explained thoroughly because it's probable that a shorter solution exists (with the lack of built-ins for this in mind) - I encourage you to try to beat this code length!
Explanation
| get input
! disable implicit output
I split into chars
I^ get number of chars
P reset pointer
[...]` loop N times, N = number of chars
g get the value at the pointer
n convert to ASCII int
s save to memory
F0 call local function 0 (returns -1, 0, or 1)
(-1 if a-z, 1 if A-Z, 0 otherwise)
*32 multiply by 32 (the difference between A-a, B-b, etc.)
+~ add value in memory
, output character corresponding to ASCII value
> move pointer right
: start local function 0
s save input (passed implicitly) to memory
F2 call local function 2 (returns 1 if a-z, 0 otherwise)
$ swap result with value in memory
F1 call local function 1 (returns 1 if A-Z, 0 otherwise)
-~ subtract value in memory (becomes -1 if a-z, 1 if A-Z, 0 otherwise)
: start local function 1 (checks if A-Z)
s save input (passed implicitly) to memory
<91 check if the value is <91
[1....] if <91...
g get the value in memory
>64 check if the value is >64
: start local function 2 (checks if a-z)
s save input (passed implicitly) to memory
<123 check if the value is <123
[1....] if <123...
g get the value in memory
>96 check if the value is >96
JavaScript (ES6), 56 bytes
-5 thanks to @ngn
s=>s.replace(/./g,c=>c[`to${c<{}?'Low':'Upp'}erCase`]())
JavaScript (Node.js), 45 bytes
-6 thanks to @ngn
s=>Buffer(s).map(c=>c^32*(c>>6&--c%32<26))+""
Brachylog, 8 bytes
{ụ?ḷ|ụ}ᵐ
Explanation
We check if a character is invariant by uppercasing, in which case we return the lowercase version, else we return the uppercase.
{ }ᵐ Map for each character:
ụ? If the input uppercased is still the input
?ḷ Output is the lowercased input
| Else
ụ Output is the uppercased input
K (ngn/k), 27 26 24 bytes
-1 byte thanks to @akamayu and another -1 thanks to @ngn!
ngn/K has a builtin for converting to lower case (_), but none for converting to uppercase, so there has to be some sort of codepoint arithmetic involved.
`c$32/|(0/2\1-"A[a{"')'\
Bash, 11 bytes
The ~~ operator in Bash can be used to toggle the case of all characters in a string.
echo ${1~~}
Lua, 107 bytes
o=""s=io.read()for c in s:gmatch"."do if c==c:lower()then o=o..c:upper()else o=o..c:lower()end end print(o)
Explanation
First time golfing with Lua, and also the first time I'm officially making a proper program with it 😇
We create two strings for our output and input.
o = ""
i = io.read()
Then we use a generator function that yields the matched group expression as the loop repeats (for lack of true understanding, this is what I can come up as a description). Using . ensures that gmatch returns individual characters.
for c in s:gmatch"." do
-- ...
end
In the loop we do a test, if the character is lower-case already, we convert it to upper-case. Note that this test automatically lets uncased characters like punctuation and numbers to pass, since they stay the same.
After the conversion, we concatenate the character to the output string.
if c == c:lower() then
o = o .. c:upper()
else
o = o .. c:lower()
end
Then we print the output string
print(o)
--
Full un-golfed code
o = ""
s = io.read()
for c in s:gmatch"." do
if c == c:lower() then
o = o .. c:upper()
else
o = o .. c:lower()
end
end
print(o)
Java 10, 64 bytes
s->{for(var c:s)System.out.print(c>64&c<91|c>96&c<123?c^=32:c);}
Input as a character-array; output is printed directly to STDOUT.
Explanation:
s->{ // Method with character-array parameter and no return
for(var c:s) // Loop over the characters of the input:
System.out.print( // Print:
c>64&c<91|c>96&c<123?
// If the character is a letter:
c^=32 // Invert its case by XOR-ing the codepoint by 32 (the `^=`
// instead of `^` is so it'll remain a character instead of
// becoming an integer)
: // Else (it's not a letter):
c);} // Print the character as is
Excel, 71 bytes
=LET(c,MID(A1,ROW(A:A),1),d,LOWER(c),CONCAT(IF(EXACT(c,d),UPPER(c),d)))
Input is in the cell A1. Output is wherever the formula is. I feel like there should be a shorter way to do this but Excel is limited in its case-switching functions.
The LET() function allows you to define variable as a name,value pair. This saves us bytes by letting us reference data by a shorter name.
c,MID(A1,ROW(A:A),1)breaks the input into individual characters. In the latest versions of Excel,ROW(A:A)will have a max value of 2^20 and the characters in a cell are limited to 2^15 so this will cover all cases.d,LOWER(c)converts each character into its lowercase regardless of how it started.CONCAT(IF(EXACT(c,d),UPPER(c),d))checks each original character to see if it matches the lowercase version and, if it does, returns the uppercase version. Otherwise, it returns the lowercase. We have to useEXACT()becausec=dis case-insensitive. TheCONCAT()parts just re-combines all those individual characters into a single string.
APL+WIN, 42 bytes
Prompts for input. Code adjusted to account for difference between APL+WIN atomic vector and that of Dyalog Classic
⎕av[m+∊+/48 ¯48×(⊂m←⎕av⍳⎕)∊¨(⊂⍳26)+¨17 65]
MathGolf, 7 bytes
ô∙!=¿δ!
Explanation:
ô # Loop over the characters of the (implicit) input-string,
# using the following 6 characters as inner code-block:
∙ # Triplicate the current character
! # Lowercase the top copy
= # Pop the top two, and check whether they're still equal
¿ # If they were equal (aka the character was lowercase, or not a letter):
δ # Uppercase the character
¿ # Else (it was an uppercase character)
! # Lowercase the character instead
# (after the loop, the entire stack is joined together and output implicitly)
05AB1E (legacy) / 2sable, 1 byte
š
Try it online in 05AB1E (legacy) or try it online in 2sable.
05AB1E, 2 bytes
.š
Explanation:
Builtin to switch the case of all ASCII letters in the (implicit) input-string, after which the result is output implicitly.
Haskell, 64 58 bytes
-6 bytes thanks to Bubbler.
import Data.Char
f s=[last(toUpper:[toLower|c<'a'])c|c<-s]
I wish there were a more interesting solution but it probably looks like:
85 bytes
f s=[last$c:[toEnum$o-(signum$o-91)*32|64<o&&o<91||96<o&&o<123]|c<-s,o<-[fromEnum c]]
...Yeah. Gross. There's also:
98 bytes
f s=[last$c:[n|(Just n)<-[m]]|c<-s,m<-[lookup c$zip['a'..'z']['A'..'Z']++zip['A'..'Z']['a'..'z']]]
I feel like this could get a whole lot better but I'm blanking.
K (ngn/k), 20 bytes
{`c$(_x)-32*~"a{"'x}
Lowercase the entire string using the builtin _ and then subtract 32 from those that were already lowercase to make them uppercase.
{`c$(_x)-32*~"a{"'x} x: string
"a{"'x for each char c in x, -1 if c<'a', 0 if 'a'<=c<'{',
1 if '{'<=c
32*~ boolean not times 32; gives 32 for lowercase in input
(_x) lowercase version of x
- subtract to uppercase the lowercase
`c$ convert the result of arithmetic back to char type
APL (Dyalog APL), 13 12 bytes
⊢⎕C¨⍨¯1*⎕C≠⊢
⊢⎕C¨⍨¯1*⎕C≠⊢
⊢ # input
≠ # not equal to (vectorized)
⎕C # lowercase version
¯1* # -1 ^ x (convert 0 to 1, 1 to -1)
⎕C¨⍨ # convert to uppercase where 1 and lowercase where -1
⊢ # on input
💎
Created with the help of Luminespire.
APL (Dyalog Extended), 1 byte
-
J, 16 14 bytes
3!:12"+~'`'&I.
NOTE: fails on ATO's older J but works in j9.4.2
-9 thanks to ovs!!
-2 thanks to Bubbler for a very nice refinement!
The basic clever idea is due to ovs. The idea to simplify it using "insert before" to get the upper/lower flags '`'&I. is due to Bubbler.
3!:12is the J verb for changing case -- a 0 left arg makes it downcase and a 1 makes it upcase. We add"+to change the rank and make it work on atoms.~'`'&I.Returns a boolean array with zeros where the input is less than`(lowercase), and ones elsewhere (uppercase).- That boolean array, in its entirety, is the left arg to
3!:12, and the original input is the right arg. Since we are operating on atoms, it flips the case of each letter.
J, 24 bytes
g`tolower@.(=g=.toupper)
-1 thanks to ovs for this variant using agenda!
This showcases an interesting fact about agenda, which is that if you provide it a list of integers, it runs on each on separately, returning a list of results.
So it applies 'tolower' to every uppercase letter, and toupper to every lowercase one.
J, 27 25 bytes (original)
(=0{g)`(g=.3!:12"{~&0 1)}
Attempt This Online! (NOTE: fails on ATO's older J but works in j9.4.2)
29 byte variant that works on ATO:
(=0{g)`(g=.tolower,:toupper)}
The variant is clearer for the explanation anyway:
(...)`(...)}A single application of the rarely used Item Amend.g=.tolower,:toupperConstruct all lowercase and all uppercase versions of the input:mixed case MIXED CASE=0{gBoolean vector showing where the input is lowercase:0 1 1 1 1 1 0 1 1 1Item amend then takes from the uppercase version at each 1 index, and from the lowercase version at each 0 index.
Go, 142 bytes
import(q"strings";."unicode")
func f(s string)string{return q.Map(func(r rune)rune{if IsUpper(r){r=ToLower(r)}else{r=ToUpper(r)};return r},s)}
One of the few times Go provides a Map function, and it's on strings.
PowerShell Core, 42 bytes
$args|%{[char]($_-bxor32*($_-in"a".."z"))}
Takes an array of characters as input
Returns an array of characters
Japt v2.0a0, 9 bytes
®c^H*Zè\l
®c^H*Zè\l
® # Map each character Z to:
c # It transformed by passing its charcode through:
^ # XOR with
H # 32
* # Multiplied by
Zè # Number of matches of the following regex in Z:
\l # [A-Za-z] (alphabetical)
💎
Explanation created with the help of Luminespire.
TypeScript’s type system, 141 bytes
141 bytes with capitalization builtins:
type G<C,U=Uppercase<C>,L=Lowercase<C>>=U extends L?C:C extends U?L:U
type F<S,O>=S extends`${infer C}${infer S}`?F<S,`${O&string}${G<C>}`>:O
186 bytes no builtins:
type F<S,O>=S extends`${infer C}${infer S}`?F<S,`${O&string}${"aAabBbcCcdDdeEefFfgGghHhiIijJjkKklLlmMmnNnoOopPpqQqrRrsSstTtuUuvVvwWwxXxyYyzZz"extends`${any}${C}${infer c}${any}`?c:C}`>:O
Charcoal, 10 bytes
⭆S⎇№αι↧ι↥ι
Try it online! Link is to verbose version of code. Explanation:
S Input string
⭆ Map over characters and join
α Predefined variable uppercase ASCII
№ Contains
ι Current character
⎇ If true then
ι Current character
↧ Lowercased
ι Else current character
↥ Uppercased
Implicitly print
Retina 0.8.2, 7 bytes
T`Ll`lL
Try it online! Link includes test cases. Explanation: Simply transliterates using the shortcuts for upper and lowercase letter ranges.
C (gcc), 40 bytes
f(char*s){if(*s^=isalpha(*s)/32)f(s+1);}
C (gcc), 45 42 bytes
f(char*s){if(*s^=isalpha(*s)?32:0)f(s+1);}
Acc!!, 59 bytes
N
Count i while _ {
Write _+_/65*(90/_-_/97*(122/_))*32
N
}
Explanation
Here's a slightly de-obfuscated version:
N
Count i while _ {
Write _ + (_/65)*(90/_)*32 - (_/97)*(122/_)*32
N
}
N reads a character of input and stores its ASCII code in the accumulator.
Count i while _ loops while the accumulator's value is nonzero. After the end of input (including an implicit trailing newline), N returns zero, so this loops over the entire input and then halts.
Acc!! doesn't have comparison operators, so we use integer division to determine what range a character code is in:
| _/65 | 90/_ | _/97 | 122/_ | Range |
|---|---|---|---|---|
| 0 | >= 1 | 0 | >= 1 | _ < A |
| 1 | 1 | 0 | 1 | A ≤ _ ≤ Z |
| 1 | 0 | 0 | 1 | Z < _ < a |
| 1 | 0 | 1 | 1 | a ≤ _ ≤ z |
| 1 | 0 | 1 | 0 | z < _ |
Multiplying the first two tells us the character is uppercase, in which case we add 32 to make it lowercase. Multiplying the second two tells us the character is lowercase, in which case we subtract 32 to make it uppercase. We then Write out the modified character and read another one with N.
For the golfed version, we pull the common factor of 32 out of both products, and then observe that _/65 can only ever be 0 or 1, and it's only 0 when we don't want to modify the character, so it can be pulled out as well.
Python, 12 bytes
str.swapcase
Attempt This Online! (Python 3)
Attempt This Online! (Python 2)
Pyth, 3 bytes
rQ2
Q # input
r 2 # swapcase
