| Bytes | Lang | Time | Link |
|---|---|---|---|
| 085 | AWK | 250908T201909Z | xrs |
| 009 | Thunno 2 | 230610T162443Z | The Thon |
| 045 | Zsh*+coreutils | 230131T054435Z | roblogic |
| 017 | Pyt | 230129T141630Z | Kip the |
| 022 | #MATL | 151222T162754Z | Luis Men |
| 065 | C 65 Bytes | 220402T145445Z | user1117 |
| 074 | Python 3 | 151222T110113Z | Koneke |
| 111 | TIBasic | 210914T225515Z | Youserna |
| nan | Python 3.8 | 210914T190750Z | Alan Bag |
| 012 | Pip | 210429T024415Z | DLosc |
| 091 | C gcc | 210428T182357Z | user1033 |
| 009 | Vyxal | 210428T171536Z | Aaroneou |
| 049 | Wolfram Language Mathematica | 190822T014826Z | att |
| 017 | 05AB1E | 200928T204722Z | Makonede |
| 013 | Pip | 200904T062957Z | Razetime |
| 021 | Keg | 190821T221030Z | lyxal |
| 093 | Python 3 | 190907T171542Z | Sagittar |
| 084 | Python 3 | 190822T010207Z | Dat |
| 075 | Zsh | 190822T004348Z | GammaFun |
| 193 | C# .NET | 190820T163100Z | canttalk |
| 103 | Ink | 190227T021419Z | Sara J |
| 008 | Brachylog | 190228T075027Z | Unrelate |
| 009 | Japt | 190227T035915Z | Oliver |
| 080 | R | 180809T133241Z | JayCe |
| 040 | Noether | 180809T142522Z | Beta Dec |
| 091 | Scala | 171117T210234Z | sprague4 |
| 011 | Jelly | 171117T183532Z | Erik the |
| 094 | C gcc | 171117T053442Z | MD XF |
| 075 | REXX | 171113T200433Z | idrougge |
| 024 | APL Dyalog Unicode | 171110T180803Z | J. Sall& |
| 022 | APL Dyalog | 171113T180659Z | Adá |
| 114 | Excel VBA | 171111T213720Z | Taylor R |
| 075 | R | 160722T073139Z | Andre |
| 069 | Java SE 8 | 171109T195417Z | jfh |
| 116 | Powershell | 170915T130428Z | Ally Wil |
| 073 | Python 2 | 170915T094437Z | lynn |
| 032 | Ly | 170915T051046Z | LyricLy |
| 013 | Recursiva | 170910T064408Z | 0xffcour |
| 005 | TeaScript | 151222T204555Z | Downgoat |
| 104 | AWK | 170614T014510Z | Arc676 |
| 060 | PHP | 170606T203814Z | Titus |
| 016 | 05AB1E | 170519T004044Z | Neil A. |
| 050 | Perl 6 | 161214T213308Z | bb94 |
| 097 | Lua | 151222T095118Z | Katenkyo |
| 043 | Ruby | 151222T103807Z | manatwor |
| 099 | Java 7 | 160928T180126Z | Geobits |
| nan | Ruby | 151222T223630Z | histocra |
| 023 | Perl | 160915T190522Z | Ton Hosp |
| 083 | Python 3 | 151222T084252Z | Sherlock |
| 040 | slang | 160721T152149Z | MCMaster |
| 207 | Sprects | 160721T112726Z | Erik the |
| nan | Ruby | 151226T175824Z | Shelvacu |
| 142 | Swift 2 | 151222T181057Z | Jojodmo |
| 111 | SpecBAS | 151222T110247Z | Brian |
| 024 | k4 | 151223T195224Z | Aaron Da |
| 078 | JavaScript ES6 | 151223T182332Z | Mwr247 |
| 068 | MATLAB | 151222T134351Z | brainkz |
| 125 | Mouse2002 | 151223T185237Z | cat |
| 079 | Python 2.7.10 | 151222T163434Z | Daniel |
| 033 | Perl | 151222T211918Z | Kenney |
| 165 | Java | 151223T132937Z | Minimal |
| 017 | Jolf | 151223T043911Z | Conor O& |
| 062 | Retina | 151222T153040Z | NinjaBea |
| 088 | Python 2.7 | 151222T230458Z | Patrick |
| 067 | Python 2 | 151222T211823Z | xnor |
| 061 | Sed | 151222T213057Z | manatwor |
| 081 | Python | 151222T132348Z | PurkkaKo |
| 062 | PHP | 151222T101308Z | insertus |
| 071 | C function | 151222T182949Z | Digital |
| 017 | Seriously | 151222T181318Z | quintopi |
| 018 | CJam | 151222T133820Z | lynn |
| 075 | Mathematica | 151222T123111Z | LegionMa |
| 060 | Gema | 151222T115342Z | manatwor |
| 023 | LabVIEW | 151222T094145Z | Eumel |
| 079 | JavaScript ES6 | 151222T084907Z | user8165 |
| 010 | Pyth | 151222T084622Z | izzyg |
| 048 | Haskell | 151222T084048Z | nimi |
AWK, 85 bytes
BEGIN{t="abcdefghijklmnopqrstuvwxyz"}/[a-z]/&&$0=t
/[A-Z]/&&$0=toupper(t)
/[^A-z]/&&1
Thunno 2, 9 bytes
A?fh?kA:Ạ
Thunno 2, 13 bytes
ẠD$Ƈ?:RD$Ƈ?:$
Explanation
A?fh?kA:Ạ # Implicit input
A? # If it's alphabetic:
fh? # If it's uppercase:
kA # Push the uppercase alphabet
: # Otherwise:
Ạ # Push the lowercase alphabet
# Otherwise, the input remains on top
# Implicit output
ẠD$Ƈ?:RD$Ƈ?:$ # Implicit input
ẠD # Push the lowercase alphabet and duplicate
$Ƈ # Pop one copy and check if the input is in it
? # If it is, do nothing, leaving the lowercase alphabet
# on the top of the stack to be implicitly output
: # Otherwise:
RD # Push the uppercase alphabet and duplicate
$Ƈ # Pop one copy and check if the input is in it
? # If it is, do nothing, leaving the uppercase alphabet
# on the top of the stack to be implicitly output
:$ # Otherwise, push the input
# Implicit output of top of stack
Zsh*+coreutils, 45 bytes
l=${(j::):-{a-z}};<<<"$l
$l:u"|grep $1||<<<$1
(*) Using setopt braceccl to save 1 byte
Pyt, 17 bytes
ĐĐʊɔ?ĉʊ:ŕɫɔ?ĉɫ:ŕ;
ĐĐ implicit input; duplicate twice on stack
ʊɔ?ĉʊ: is it a lowercase letter? if so, push lowercase letters
ŕɫɔ?ĉɫ: else is it an uppercase letter? if so, push uppercase letters
ŕ otherwise, leave input on stack
; end if-then-else statements; implicit print
#MATL, 22 bytes
jtt1Y2XIm~Iw?km?Ik]]1$
This uses the current version (3.1.0) of the language.
EDIT (Sep 15, 2017): Try it at MATL Online! (with a newer version of the language).
###Examples
>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> e
abcdefghijklmnopqrstuvwxyz
>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> T
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> "
"
###Explanation
j % input string (assumed to be a single character)
tt % duplicate twice
1Y2 % predefined literal: uppercase letters
XI % copy to clipboard I
m~ % check if not member
I % paste from clipboard I
w % swap elements in stack
? % if
k % convert string to lowercase
m % check if member
? % if
I % paste from clipboard I
k % convert string to lowercase
] % end
] % end
1$ % input specification for implicit printing
C - 65 Bytes
f(c){for(c=islower(c)?97:c>64&c<91?65:c;(putchar(c++)|32)<122;);}
Thanks to @ceilingcat for -5 bytes
Ungolfed (original version)
i = 65;
f(c)
{
if(isalpha(c))
while(i < 91)
putchar(c & 32 | i++);
else
putchar(c);
}
Explanation
A function that receives an integer (the input character) and prints it if it is not a letter or prints the entire alphabet with the capitalization of the input character.
Python 3, 92 84 82 74 bytes
Current version: 74, thanks to isaacg and wnnmaw!
lambda c:(c,''.join(chr(x+(67,97)[c>'Z'])for x in range(25)))[c.isalpha()]
Ungolfed: (for some definition of ungolfed)
lambda c:
(
c,
''.join([chr(x + (67,97)[c > 'Z']) for x in range(25)])
)
[c.isalpha()]
First version: 92
def f(c):print(''.join([chr(x+(97if c>'Z'else 65)) for x in range(25)])if c.isalpha()else c)
Second version: 82, thanks to isaacg! :)
lambda c:''.join(chr(x+(97if c>'Z'else 65))for x in range(25))if c.isalpha()else c
TI-Basic, 111 bytes
Input Str1
"inString(Ans,Str1→u
"ABCDEFGHIJKLMNOPQRSTUVWXYZ
If u
Stop
"abcdefghijklmnopqrstuvwxyz
If u
Stop
Str1
Output is stored in Ans.
Python 3.8, 108 93 bytes
-15 bytes thanks to Aaron Miller
a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(a if(x:=input())in a else a.lower()if x.islower()else x)
Pip, 12 bytes
aN_FI[zAZ]|a
Razetime's answer is the approach I thought of too, but 13 bytes seemed rather long. So I went looking for other approaches...
[zAZ] List containing the lowercase alphabet and the uppercase alphabet
FI Filter on this function:
aN_ Is the command-line argument in each string?
If the argument is lowercase, the result is the lowercase alphabet*; if
it's uppercase, the result is the uppercase alphabet*; and if it's
neither, the result is an empty list, so...
|a Logical OR with the argument: if filter result is [], print arg instead
* As a single-element list, but without flags, that doesn't affect how it is displayed
C (gcc), 91 bytes
A function that accepts a char and prints the result via stdout (91 bytes):
f(x){puts(isalpha(x)?x>90?"abcdefghijklmnopqrstuvwxyz":"ABCDEFGHIJKLMNOPQRSTUVWXYZ":&x);}
Bonus (a shorter version of MD XF's answer, since I don't have enough reputation to comment (90 bytes):)
#define f(x)isalpha(x)?x>90?"abcdefghijklmnopqrstuvwxyz":"ABCDEFGHIJKLMNOPQRSTUVWXYZ":&x
Vyxal, 9 bytes
Ǎ[æ[kA|ka
Explanation:
# Implicit input
Ǎ[ # If input is a letter:
æ[ # If input is capitalized:
kA # Push 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
| # Else:
ka # Push 'abcdefghijklmnopqrstuvwxyz'
# Implicit output
Wolfram Language (Mathematica), 62 49 bytes
#/.(#|##->""<>##&)@@@{A=Alphabet[],Capitalize@A}&
05AB1E, 17 bytes
AsAus©åiAuë®åiAë®
Try it online or verify all test cases.
# (implicit) push STDIN to stack
A # push "abcdefghijklmnopqrstuvwxyz"
s # swap top two values of stack
Au # push "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
s # swap top two values of stack
© # store top of stack in register_c
åi # if top of stack in second-to-top of stack...
Au # push "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ë®åi # elif value of register_c in second-to-top of stack...
A # push "abcdefghijklmnopqrstuvwxyz"
ë # else...
® # push value of register_c
# (implicit) output top of stack to STDOUT
Keg, -ir 45 37 21 bytes
:AZ"•[_AZɧ|:az"•[_azɧ
-16 bytes due to using ranges
Answer History
37 bytes
::`>$\~<*[_z(|:;)^|:A1->[_Z(|:;)^|,
-8 bytes thanks to A__
Python 3, 93 bytes
i=input();a="abcdefghijklmnopqrstuvwxyz";A=a.upper();print(i in a and a or i in A and A or i)
Under 100 bytes!
Python 3, 84 bytes
lambda x,a='abcdefghijklmnopqrstuvwxyz':[x,a,a.upper()][(x in a)+2*(x in a.upper())]
Zsh, 75 bytes
l=${(j::):-{a..z}} u=$l:u
<<<${${${l:#*$1*}:+${${${u:#*$1*}:+$1}:-$u}}:-$l}
l=${(j::):-{a..z}} # set l to the (j::)oined lowercase
u=$l:u # set u to :uppercase'd l
<<<${${${l:#*$1*}:+${${${u:#*$1*}:+$1}:-$u}}:-$l}
${l:#*$1*} # remove *$1* from $l (is empty if $1 is lower)
${ :+ } # If non-empty, then...
${u:#*$1*} # remove *$1* from $u (is empty if $1 is upper)
${ :+$1} # If non-empty, substitute $1
${ :-$u} # If empty, substitute $u
${ :-$l} # If empty, substitute $l
C# .NET, 193 bytes
class P{static void Main(string[]a){var z="ABCDEFGHIJKLMNOPQRSTUVWXYZ";var b=a[0];System.Console.Write(b.Length>1?b:z.IndexOf((b[0]))>-1?z:z.ToLower().IndexOf((b[0]))>-1?z.ToLower():b[0]+"");}}
Try Online EDIT: Variable assignment with if statements is stupid
Ink, 103 bytes
VAR u="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
VAR l="abcdefghijklmnopqrstuvwxyz"
=o(c)
{u?c:{u}|{l?c:{l}|{c}}}->->
Brachylog, 8 bytes
∈Ạ|ḷ∈Ạụ|
∈Ạ The input is a member of the lowercase alphabet,
| which is output, or
ḷ∈Ạ the input lowercased is a member of the lowercase alphabet,
ụ| which is output uppercased, or the input is output.
It'd be two bytes shorter if we had a constant for the uppercase alphabet but we don't :(
R, 80 bytes
s=(r=65:90)+32
a=utf8ToInt(scan(,''));intToUtf8("if"(a%in%r,r,"if"(a%in%s,s,a)))
-1 byte thanks to Giuseppe. Still not the golfiest way (see here). Similar ideas include:
R, 87 bytes
f=function(x,y)"if"(a%in%x,x,y)
a=utf8ToInt(scan(,''));intToUtf8(f(r<-65:90,f(r+32,a)))
a=utf8ToInt(scan(,''));intToUtf8("if"(a%in%c(32:64,91:96,123:126),a,65:90+32*(a>90)))
and my favorite:
a=utf8ToInt(scan(,''));intToUtf8(c(a,65:90+32*(a>90))[2*a%in%c(32:64,91:96,123:126)-1])
and inspired by the other R solution (same bytecount):
"+"=function(x,y)"if"(a%in%x,x,y)
a=scan(,'');cat(letters+LETTERS+a,sep="")
Noether, 40 bytes
{0A~bI~a/~c}{bP}b{Ua/~d}{bUP}1{cd|-}{aP}
Uses Noether's built-in constant function A to return the string abcdefghijklmnopqrstuvwxyx.
Scala, 91 characters
(c:Char)=>{var a='a'.to('z').mkString;if(c.isUpper)a=a.toUpperCase;if(!c.isLetter)a=""+c;a}
Un-golfed
def f(c: Char): String = {
var a='a'.to('z').mkString //set up lower case default response
if (c.isUpper) {
a = a.toUpperCase //mutate the result if upper case
}
if (!c.isLetter) {
a = ""+c //mutate the result if not a letter
}
a //return result
}
Having a initial mutable result rather than returning an immutable value from 3 distinct if else blocks saved me 2 chars, even though I hate it.
Scala-thonic method
A better method for scala would be something like this:
def convertToAlphabet(c: Char): String = {
c match {
case x if !x.isLetter => x.toString
case x if x.isUpper => ('A' to 'Z').mkString
case _ => ('a' to 'z').mkString
}
}
C (gcc), 94 bytes
#define f(c)isupper(c)?"ABCDEFGHIJKLMNOPQRSTUVWXYZ":islower(c)?"abcdefghijklmnopqrstuvwxyz":&c
#define f(c) is like declaring a function f that takes a variable c.
isupper(c) checks if c is an uppercase letter, returns the uppercase alphabet if so. Otherwise, it checks if it's lowercase. If so, it returns the lowercase alphabet. Otherwise, it returns a pointer to c, which can be printed as a string (since you must pass a char or int to f).
REXX, 75 bytes
b=arg(1)
a=xrange(a,z)
if b>z then a=lower(a)
if verify(b,a) then a=b
say a
APL (Dyalog Unicode), 26 24 bytes
t←{⍵∊g←819⌶f←⎕A:g⋄⍵∊f:f⋄⍵}
The byte count does not include t← because it's not necessary, it just assigns the function to t (so you can call it by using t input).
If input is not a number, it needs to be enclosed in single quotes. For the input ', you need to escape it by typing it twice (so the call is t '''')
Thanks to @Adám for 2 bytes.
How it works:
{⍵∊g←819⌶f←⎕A:g⋄⍵∊f:f⋄⍵} ⍝ Main function
: ⍝ if
f←⎕A ⍝ Assigns the uppercase alphabet to f
g←819⌶ ⍝ Assigns the I-Beam command 819 (case convert) over the uppercase alphabet (f) to g
⍵∊ ⍝ The right argument 'is in' the lowercase alphabet
g ⍝ then print g (the lowercase alphabet)
⋄ : ⍝ else if
⍵∊f ⍝ the right argument 'is in' f (the uppercase alphabet)
f ⍝ print f
⋄⍵ ⍝ else, print the right argument.
APL (Dyalog), 22 bytes
Unnamed prefix lambda.
{⊃a/⍨⍵∊¨a←⎕A(819⌶⎕A)⍵}
{…} anonymous function where ⍵ represents the argument:
⎕A(819⌶⎕A)⍵ uppercase Alphabet, lowercased Alphabet, argument
a← store in a (for all)
⍵∊¨ three Booleans for argument's membership of each those
a/⍨ filter a by that
⊃ pick the first
Excel VBA, 114 Bytes
Anonymous VBE immediate window function that takes input and outputs to the VBE immediate window.
a=Asc([A1]):i=IIf(a>64And a<91,64,(a>96And a<123)*-96):?IIf(i=0,[A1],"");:If i>0 Then For j=1To 26:?Chr(i+j);:Next
R, 90 75 bytes
a=scan(,'');l=letters;L=LETTERS;cat("if"(a%in%l,l,"if"(a%in%L,L,a)),sep="")
Thanks to Giuseppe.
Old version (90 bytes):
a=scan(,'');l=letters;L=LETTERS;if(a%in%l)cat(l,sep="")else if(a%in%L)cat(L,sep="")else a
Looks ugly, but those cats cannot be outsourced to functions, IMHO.
Java SE 8, 71 69 bytes
Golfed:
(a,s)->{char b=97;if(a<91)b-=32;a=b;b+=26;while(a<b)s+=a++;return s;}
Ungolfed:
(a,s)->{ // String as a parameter. If declaration is necessary it adds 8 bytes
char b = 97; // Uppercase A char, this is important
if (a < 91) // If it is not past 'z', where a is a char param
b -= 32; // Then go back to the lowercase alphabet
a = b; // Done to prevent a cast
b += 26; // End of alphabet
while (a < b) // Go to end of alphabet
s += a++; // Append character
return s;} // Then return
I had originally implemented the following
String s="";char b=96;if(a-91<0)b-=32;for(char c=b;++c<b+27;)s+=c;return s;
It's more elegant but sadly it's one byte larger. This is assuming that behavior for non alpha characters is undefined and string s is initialized to "" prior to execution. Be gentle it's my first post.
edit: 2 bytes saved by Stewie Griffin by changing
a - 91 < 0 to a < 91
Powershell, 116 bytes
$b='j';$a='ABCDEFGHIJKLMNOPQRSTUVWXYZ';switch($b){{$b-cmatch'[a-z]'}{$a.ToLower()}{$b-cmatch'[A-Z]'}{$a}default{$_}}
Change $b='j' to modify result.
I couldn't figure out a way to get the alphabet that was shorter than just writing the alphabet unfortunately.
e.g. (65..90|%{[char][byte]$_})-join''
Python 2, 73 bytes
c=ord(input())
print[chr(c),bytearray(range(c&96|1,c&96|27))][64<c&95<91]
Ly, 32 bytes
"AZ"Ris~[p&o;]&p"az"Rl~[p&o;]lo;
Explanation:
"AZ"Ris~[p&o;]&p"az"Rl~[p&o;]lo;
is # take input and save it
"AZ"R ~[ ] # is it in the uppercase alphabet?
p&o; # output the stack, terminate
&p # clear stack
l # load input
"az"R ~[ ] # is it in the lowercase alphabet?
p&o; # output the stack, terminate
lo; # output the input, terminate
Recursiva, 13 bytes
||&N(a(&N)a)a
Explanation:
This roughly translates to 'N(a and (' or 'N)a and )' or a. N(a checks if a is in (. ( and ) are upper and lower-case alphabet yield.
TeaScript, 5 bytes
xN(0)
TeaScript has a (almost) built-in for this :D
Try it online (note: the online interpreter has been updated to TeaScript v3 so in which this is N0)
TeaScript 3, 2 bytes [non-competing]
Using TeaScript 3, this can become 2-bytes. This is non-competing because TeaScript 3 was made after this challenge
N0
1 byte alternative
If we could output 0123456789 for digits, then this could be:
°
AWK 104 bytes
/[a-z]/{print"abcdefghijklmnopqrstuvwxyz"}
/[A-Z]/{print"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
/[^A-z]/{print$0}
PHP, 60 bytes
for(ctype_alpha($c=$argn)?$c=$c&a|A:$z=25;$z++<26;)echo$c++;
Run as pipe with -R.
05AB1E, 19 16 bytes
-3 bytes thanks to else
DAsåiAëDAusåiAuë
How it works
# implicit input
D # duplicate
A # push lowercase alphabet
s # swap last two elements
å # push a in b
i # if
A # lowercase alphabet
ë # else
D # duplicate
Au # uppercase alphabet
s # swap last two elements
å # push a in b
I # if
Au # uppercase alphabet
ë # else leave input
# implicit print
Perl 6, 50
{join "",/<:Lu>/??"A".."Z"!!/<:Ll>/??"a".."z"!!$_}
Lua, 98 97 bytes
Sadly, I didn't find a solution shorter than 26 bytes to set a with the alphabet. In fact, I didn't find shorter than 32.
Edit : save 1 Byte thanks to @ATaco, was doing this error a lot when started with Lua :p
c=io.read()a="abcdefghijklmnopqrstuvwyz"print(not c:find"%a"and c or c:find"%u"and a:upper()or a)
You can test it online on the official site or on ideone. If you use the former, the input won't work (disabled), so use the following source, where it is wrapped into a function.
function f(c)
a="abcdefghijklmnopqrstuvwyz"
print(not c:find"%a"and c or c:find"%u"and a:upper()or a)
end
print(f("\""))
print(f("a"))
print(f("Q"))
Ruby, 46 43 characters
(42 characters code + 1 character command line option)
[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}
Thanks to:
- Jordan for the
===magic (-3 characters)
Sample run:
bash-4.3$ echo -n 'm' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
abcdefghijklmnopqrstuvwxyz
bash-4.3$ echo -n 'W' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
ABCDEFGHIJKLMNOPQRSTUVWXYZ
bash-4.3$ echo -n '@' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
@
Java 7, 99 bytes
void f(char c){for(int a=c|32,i=97;i<123;i++)System.out.print(a<123&a>96?(char)(i-a+c):i<98?c:"");}
Slightly more readable, with no scrollbars:
void f(char c){
for(int a=c|32,i=97;i<123;i++) // a is lowercased input, i loops alphabet
System.out.print(
a<123&a>96? // if a is a letter
(char)(i-a+c): // subtract diff between lower and input
i<98?c:""); // else print input if first iteration
}
The logic here is pretty straightforward, but a different method than the other Java answer.
Ruby, 41 + 1 = 42
With switch -p, run
([*?A..?z]*'').scan(/\w+/){$&[$_]&&$_=$&}
This generates the string
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz
and checks each contiguous block of "word characters", which happen to be just the lowercase and uppercase alphabets and the underscore character. If there were multiple consecutive word characters between Z and a, this trick wouldn't work.
Edited to add explanation, by request:
The -p flag does essentially
while( $_ = STDIN.gets )
#execute code
print $_
end
[*?A..?z] is the array of characters between uppercase A and lowercase Z, in ASCII order. That's the uppercase alphabet, some non-letter characters, and the lowercase alphabet. *'' joins the array into a string, so we can call .scan on it. scan will find each match of the regular expression /\w+/, populate the magic variable $& with it, and call the block. Each time the block is iterated, it checks whether the matched string contains $_ and sets the output to that string if so. So if $_ is contained in either the uppercase or lowercase alphabet, it gets modified accordingly, otherwise it's unchanged.
The ungolfed version would look something like
while ($_ = STDIN.gets )
%w[ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz].each do |alphabet|
$_ = alphabet if alphabet.include?($_)
end
print $_
end
Perl, 23 bytes
Includes +2 for -nE (instead of the normal +1) to be fair to the other perl solution
Run with the input on STDIN without trailing newline:
echo -n g | perl -lnE 'say/\pL/?a&$_|A..Z:$_'
Just the code:
say/\pL/?a&$_|A..Z:$_
Python 3, 118 105 98 97 83 bytes
Simple solution. EDIT: Golfed with thanks to Erik the Golfer's suggestion.
lambda s,a='ABCDEFGHIJKLMNOPQRSTUVWXYZ':(s,(a,a.lower())[s.islower()])[s.isalpha()]
Ungolfed:
def f(s):
a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if s.isalpha():
if s.islower():return a.lower()
else:return a
return s
s-lang, 40 bytes (non-competing)
Replaces any letter with the alphabet, matching the case.
t@[[a-z]][abcdefghijklmnopqrstuvwxyz]
- t Replace with regex function
- @ Match case for entire match parameter for t function
- [[a-z]] first argument ([a-z]) regex for matching any letter (@ parameter makes it so this function ignores the case when matching, so we don't need A-Z too)
- abcdefghijklmnopqrstuvwxyz what to replace it with
Try it here
Sprects, 207 bytes
|<CHAR>|ZA|YA|XA|WA|VA|UA|TA|SA|RA|QA|PA|OA|NA|MA|LA|KA|JA|IA|HA|GA|FA|EA|DA|CA|BA|AABCDEFGHIJKLMNOPQRSTUVWXYZ|za|ya|xa|wa|va|ua|ta|sa|ra|qa|pa|oa|na|ma|la|ka|ja|ia|ha|ga|fa|ea|da|ca|ba|aabcdefghijklmnopqrstuvwxyz
Enter character on <CHAR>.
Ruby, 56+2 = 58 bytes
2 bytes for -p flag
c=$_[0]
[?a..?z,?A..?Z].map{|r|r===c&&c=r.to_a.join}
p c
Ungolfed version (no -p flag)
while true
char = gets.chars.first
[("a".."z"),("A".."Z")].each do |range|
char = range.to_a.join("") if range.include? char
end
p char
end
Swift 2, 142 Bytes
func d(s:String)->String{let a="abcdefghijklmnopqrstuvwxyz";for v in s.utf8{return v>64&&v<91 ?a.uppercaseString:(v>96&&v<123 ?a:s)};return s}
Ungolfed
func d(s: String) -> String{
let a="abcdefghijklmnopqrstuvwxyz"
for v in s.utf8{
return (
v > 64 && v < 91 ?
a.uppercaseString :
(
v > 96 && v < 123 ?
a :
s
)
)
}
return s
}
SpecBAS, 111 bytes
I've been through several versions of this, 111 seems to be the best I can manage.
1 INPUT l$: a$="abcdefghijklmnopqrstuvwxyz"
2 ?IIF$(l$ IN ["a" TO "z","A" TO "Z"],IIF$(l$=UP$ l$,UP$ a$,a$),l$)
Line 2 uses the ? shortcut for PRINT and nested inline IF statements
Pseudo code explanation
IF character IN "a".."z","A".."Z"
THEN
IF character = UPPERCASE character
THEN
print UPPERCASE alphabet
ELSE
print alphabet
ENDIF
ELSE
print the character
ENDIF
k4, 24 bytes
{*b@&x in/:b:(.Q`A`a),x}
Another port of the Pyth answer—constructs a list of upper, lower, and the arg, and returns the first one that contains the arg.
JavaScript (ES6), 99 87 79 78 bytes
x=>(y='abcdefghijklmnopqrstuvwxyz',parseInt(x,36)>9?x>'`'?y:y.toUpperCase():x)
Uses the short array fill trick to allocate space, then just math and Thought it would be shorter until I realized the rule about non-alphabet characters. String.fromCharCode to get the alphabet.parseInt turned out to be helpful in determining if the character was in the alphabet.
Test
var F=x=>(y='abcdefghijklmnopqrstuvwxyz',parseInt(x,36)>9?x>'`'?y:y.toUpperCase():x)
x = <input type="text" oninput="result.textContent=this.value?F(this.value):''" />
<pre id="result"></pre>
MATLAB: 71 68 bytes
i=input('');b=i<65|i>122|(i>90&i<97);[i*b,~b*((65:90)+32*(i>96)),'']
(thanks to OP for saving 3 bytes)
Test:
i='a'
ans=
abcdefghijklmnopqrstuvwxyz
i='A'
ans=
ABCDEFGHIJKLMNOPQRSTUVWXYZ
i='~'
ans=
~
Explanation:
Uppercase alphabet occupies 65:90 ASCII characters. Lowercase alphabet is at 97:122 ASCII. So, b=i<65|i>122|(i>90&i<97) checks whether the input character i is NOT alphabetic. If so, input is returned. The uppercase alphabet is returned if b==1 and i<97 (uppercase character). If b==1 and i>96, 32 is added to 65:90 that corresponds to 97:122 - the lowercase alphabet.
Mouse-2002, 125 bytes
... or 126 bytes if I can't assume a REPL envrironment (which assumes a $ at the end of the program; the non-REPL interpreter crashes without one)
An attempt at code deduplication... probably a failed one.
Golfed:
?'a:123b:a.65<a.31>*1=a.90>a.97<*1=+a.122>+1=[a.!']a.63>a.91<*1=[65i:(i.91<^i.!'i.1+i:)]a.96>a.b.<*1=[97i:(i.b.<^i.!'i.1+i:)]
Ungolfed:
?' a: ~ a = getchar();
123 b: ~ b = 123
a. 65 < ~ return whether a < 65
a. 31 > ~ same for 31
* 1 = ~ AND
a. 90 > ~ a > 90 ?
a. 97 < ~ a < 97 ?
* 1 = ~ AND
+ ~ OR
a.122 > ~ a > 122 ?
+ 1 = ~ OR
[ ~ if 1
a.!' ~ print ascii codepoint
] ~ fi
a. 63 > ~ a > 63 ?
a. 91 < ~ a < 91 ?
* 1 = ~ AND
[ ~ if 1
65 i: ~ for i = 65;
( ~ do;
i. 91 < ^ ~ i < 91;
i.!' ~ print(charAt(i));
i. 1+ i: ~ i++;
) ~ done;
] ~ fi
a. 96 > ~ a > 96 ?
a. b. < ~ a < b ?
* 1 = ~ AND
[ ~ if 1
97 i: ~ for i = 97;
( ~ do;
i. b. < ^ ~ i < 91;
i.!' ~ print(charAt(i));
i. 1+ i: ~ i++;
) ~ done;
] ~ fi
$ ~ \bye
Python 2.7.10, 95 93 79 bytes
This is my first time even attempting to golf, so please, any help or advice is extremely appreciated!
from string import*
lambda i:(i,(uppercase,lowercase)[i.islower()])[i.isalpha()]
Thanks to Morgan Thrapp for the help!
Perl, 46 34 33 bytes
includes +2 for -nE
say/[a-z]/?a..z:/[A-Z]/?A..Z:$_
Run as
perl -nE 'say/[a-z]/?a..z:/[A-Z]/?A..Z:$_'
- update 34 save 12 bytes by omitting
forand using barewords, thanks to @Dom Hastings. - update 33 save 1 byte using
-Eandsayinstead ofprint.
Java, 165 characters
class A {public static void main(String[]p){int c=p[0].charAt(0),d=c|32,b=(d-96)*(d-123),e=b<0?65|(c&32):c,f=e+(b<0?26:1);for(;e<f;e++){System.out.print((char)e);}}}
Generates the required output to stdout (rather than returning it). Input is via the runtime arguments.
How it works.
1) Setup some integer variables
c = the ASCII value of the first character of the first parameter of the runtime arguments.
d = c converted to lowercase ASCII value (by ORing it with 32)
b = calculation to see if d is a letter. Will be <0 if a letter.
e = The start character for output. If ASCII value in d is a letter (see b) then it is set to 'A' (or 'a' by adding c AND 32 to 'A' ASCII value) else it is set to the original value of c.
f = the number of characters to output. If it not a letter (see b) then this is set to 1 else it is set to 26
2) Loop from e to e+f outputing each character to stdout.
Jolf, 17 bytes
? hpLipl? hpUipui
? if
hpL the lowercase alphabet (array) contains
i the input
pl return the lowercase alphabet (string)
? else if
hpU the uppercase alphabet (array) contains
i the input
pu return the uppercase alphabet (string)
i otherwise, return the input
implicit: print the result
Retina, 62 bytes
[a-z]
abcdefghijklmnopqrstuvwxyz
[A-Z]
ABCDEFGHIJKLMNOPQRSTUVWXYZ
The two short lines are the regex to match. If the input is lowercase (in the range [a-z]), it replaces that character (in this case, that is the entire input) with the lowercase alphabet. The process is similar for uppercase. If it's not a letter, no replacements are made, and it is outputted untouched.
Python 2.7, 88 bytes (incl. print)
from string import*
def f(c):print[c,uppercase,c,lowercase,c][sorted('@Z`z'+c).index(c)]
Python 2, 67 bytes
f=lambda c,i=26:c[c.isalpha():]or c*i and f(c,i-1)+chr(i^ord(c)&96)
For letter inputs, generates the string of letters recursively. Doing ord(c)&96 removes the 5 high bits, and the xor'ing the values i from 1 to 26 gives the letter char codes. For control flow, we count i down, adding new letters to the end, stopping when i=0. When the input c is not a letter, immediately outputs it and stops.
Thanks to Mauris for 2 bytes.
Previous solution (68):
lambda c:[c,str(bytearray(range(ord(c)&96,255)[1:27]))][c.isalpha()]
Sed, 61 characters
(60 characters code + 1 character command line option)
s/[a-z]/&abcdefghijklmnopqrstuvwxyz/i
s/[A-Z].*/\U&/
T
s/.//
Sample run:
bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< 'm'
abcdefghijklmnopqrstuvwxyz
bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< 'W'
ABCDEFGHIJKLMNOPQRSTUVWXYZ
bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< '@'
@
Python, 81 bytes
f=lambda z,a="abcdefghijklmnopqrstuvwxyz":[k for k in[a,a.upper(),z]if z in k][0]
This is basically a translation of the Pyth answer. It defines a function f that takes as argument the character and returns the result.
PHP, 62 76 82 bytes
PHP is doing OK now:
<?=ctype_alpha($x=$argv[1])?join(range(Z<$x?a:A,Z<$x?z:Z)):$x;
Takes an input from command line, like:
$ php alphabet.php A
$ php alphabet.php "a"
$ php alphabet.php " "
$ php alphabet.php _
Edits
- Saved 6 bytes by replacing
91>ord($x)withZ<$x. Thought way to complicated. Thanks to manatwork. - Saved 14 bytes by removing
strtoupperand building the demanded range directly.
C (function), 71 bytes
f(s,n,c){n=1;if(isalpha(s))s-=s%32-1,n=26;for(c=s;c<s+n;)putchar(c++);}
Seriously, 17 bytes
;;ú(úíuIúû;(@íuI
Hex Dump:
093b3ba328a3a17549a3963b2840a17549
Given that it pretty much just reads in an unformatted byte, checks if it's in the lowercase alphabet, then checks if it's in the uppercase alphabet, the automatic documentation given in the link is sufficient. (Note, however, that the documentation for í has the argument order reversed; it pops the sequence first.)
CJam, 18 bytes
'[,65>_elr:R]{R&}=
'[,65> pushes the uppercase alphabet, _el the lowercase alphabet, and r:R a single-char string that is read from STDIN and assigned to variable R. These are wrapped in an array (]) and the first one that has any chars in common with R is selected using {R&}=.
Mathematica, 75 bytes
#/.Thread[Join[a=Alphabet[],b=ToUpperCase@a]->Array[""<>If[#>26,b,a]&,52]]&
Pretty good score for a non-golfing language... Any solutions using character code processing would take more bytes, due to the costs of ToCharacterCode and FromCharacterCode.
Gema, 60 characters
\A=@set{a;abcdefghijklmnopqrstuvwxyz}
<J>=$a
<K>=@upcase{$a}
Sample run:
bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< 'm'
abcdefghijklmnopqrstuvwxyz
bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< 'W'
ABCDEFGHIJKLMNOPQRSTUVWXYZ
bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< '@'
@
LabVIEW, 23 LabVIEW Primitives
The selector (the ? on the cse structure) is connected to a vi that is called Lexical Class. It ouputs numbers from 1-6 depending on input, 5 is lower case 4 is upper case.
The for loop goes 26 times to create an alphabet or once to pass the symbol through.
JavaScript (ES6), 79 bytes
x=>(a="abcdefghijklmnopqrstuvwxyz",x>"`"&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x)
Explanation
JavaScript compares the code of each character alphabetically when comparing strings, so the codes of the characters used in the comparisons are 1 below and above the required range of characters.
x=>(
a="abcdefghijklmnopqrstuvwxyz", // a = lower-case alphabet
x>"`"&x<"{"?a: // if x is a lower-case letter, output alphabet
x>"@"&x<"["?a.toUpperCase(): // if x is an upper-case letter, output upper-case
x // else just output x
)
Test
var solution = x=>(a="abcdefghijklmnopqrstuvwxyz",x>"`"&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x)
X = <input type="text" oninput="result.textContent=solution(this.value)" />
<pre id="result"></pre>
Pyth, 10 bytes
h/#z[GrG1z
We start by constructing a list with 3 elements: the lowercase alphabet, the uppercase alphabet, and the input. ([GrG1z) Then, we filter this list on the number of appearances of the input in the elements being nonzero. (/#z) Finally, we take the first element of the filtered list.
Haskell, 48 bytes
f c=filter(elem c)[['a'..'z'],['A'..'Z'],[c]]!!0
Usage example:
*Main> f 'g'
"abcdefghijklmnopqrstuvwxyz"
*Main> f 'H'
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
*Main> f '\''
"'"
Take all lists of ['a'..'z'], ['A'..'Z'] and the singleton list with the input char c where c is element of. For letters we have always two matches, so we pick the first one.
