53
\$\begingroup\$

The challenge is simple:

Write a function or program that takes an input x, and outputs the lower case alphabet if x is part of the lower case alphabet, outputs the upper case alphabet if x is part of the upper case alphabet and outputs just x if it's not part of either.

Rules:

  • The input can be function argument or from STDIN
  • The input will be any of the printable ASCII characters from 32 to 126 (space to tilde).
  • The input may be inside quotation marks,'x' or "x", but remember that ' and " are valid input and should be supported.
  • The input can be any of the letters in the alphabet, i.e. you can't assume it will be a or A.
  • The output should be only one of the alphabets or the single symbol, but trailing newlines are OK.
  • The letters in the alphabet should not be separated by spaces, commas or anything else.

Some examples:

F
ABCDEFGHIJKLMNOPQRSTUVWXYZ

z
abcdefghijklmnopqrstuvwxyz

"
"

    <- Input:  Space
    <- Output: Space

Shortest code in bytes win.


Optional but appreciated: If your language has an online interpreter, please also post a link so that it can be easily tested by others.


Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=67357,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
5
  • \$\begingroup\$ Are we allowed to import packages like, in Python for example: import Random and then use Random.randint (obviously not for this challenge but still)? \$\endgroup\$
    – Daniel
    Dec 22, 2015 at 15:28
  • \$\begingroup\$ Yes, you may import packages. but the bytes for writing for instance import string are counted, thus it's often better to do workarounds. Note that the package must exist before the challenge is posted. Many challenges have something like: "Using packages that does this is not allowed", but that is not the case in this challenge. \$\endgroup\$ Dec 22, 2015 at 15:36
  • \$\begingroup\$ I'm assuming that by "quotes are valid input and must be supported" you mean that if your input method requires quotes then quotes as input would be escaped \$\endgroup\$
    – Cyoce
    Dec 23, 2015 at 5:10
  • \$\begingroup\$ May we assume a REPL environment? \$\endgroup\$
    – cat
    Dec 23, 2015 at 17:38
  • \$\begingroup\$ Is it single char input? \$\endgroup\$
    – l4m2
    Jan 29, 2023 at 23:37

76 Answers 76

2
\$\begingroup\$

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
    }
}
\$\endgroup\$
2
\$\begingroup\$

Brachylog, 8 bytes

∈Ạ|ḷ∈Ạụ|

Try it online!

∈Ạ          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 :(

\$\endgroup\$
2
\$\begingroup\$

Keg, -ir 45 37 21 bytes

:AZ"•[_AZɧ|:az"•[_azɧ

Try it online!

-16 bytes due to using ranges

Answer History

37 bytes

::`>$\~<*[_z(|:;)^|:A1->[_Z(|:;)^|,

-8 bytes thanks to A__

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ 37B by using control characters. \$\endgroup\$
    – user85052
    Aug 21, 2019 at 22:55
2
\$\begingroup\$

Pip, 13 bytes

aNz?zaNAZ?AZa

builtins.

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Is this a reference to sporeball's esolang?!?!?! \$\endgroup\$
    – lyxal
    Mar 13, 2021 at 4:35
  • \$\begingroup\$ without a doubt \$\endgroup\$
    – Razetime
    Mar 13, 2021 at 5:17
2
\$\begingroup\$

Vyxal, 9 bytes

Ǎ[æ[kA|ka

Try it Online!

Explanation:

           # Implicit input
Ǎ[         # If input is a letter:
  æ[       #   If input is capitalized:
    kA     #     Push 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      |    #   Else:
       ka  #     Push 'abcdefghijklmnopqrstuvwxyz'
           # Implicit output
\$\endgroup\$
2
\$\begingroup\$

Pip, 12 bytes

aN_FI[zAZ]|a

Try it online!

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
\$\endgroup\$
2
\$\begingroup\$

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)
\$\endgroup\$
2
2
\$\begingroup\$

TI-Basic, 111 bytes

Input Str1
"inString(Ans,Str1→u
"ABCDEFGHIJKLMNOPQRSTUVWXYZ
If u
Stop
"abcdefghijklmnopqrstuvwxyz
If u
Stop
Str1

Output is stored in Ans.

\$\endgroup\$
1
\$\begingroup\$

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}' <<< '@'
@
\$\endgroup\$
1
\$\begingroup\$

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/.//' <<< '@'
@
\$\endgroup\$
1
\$\begingroup\$

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()]
\$\endgroup\$
3
  • \$\begingroup\$ The input will be any of the printable ASCII characters from 32 to 126 (space to tilde). Wouldn't ord(c)&96 suffice, then? \$\endgroup\$
    – Lynn
    Dec 22, 2015 at 21:42
  • \$\begingroup\$ @Mauris Yes, good call. \$\endgroup\$
    – xnor
    Dec 22, 2015 at 21:47
  • \$\begingroup\$ I think '_' --> c works and saves a byte in your recursive solution. \$\endgroup\$
    – Lynn
    Dec 22, 2015 at 22:02
1
\$\begingroup\$

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)]
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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 String.fromCharCode to get the alphabet. Thought it would be shorter until I realized the rule about non-alphabet characters. 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>

\$\endgroup\$
1
  • \$\begingroup\$ x=>parseInt(x,36,y='abcdefghijklmnopqrstuvwxyz')>9?x>{}?y:y.toUpperCase():x \$\endgroup\$
    – l4m2
    Sep 16, 2021 at 20:12
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 50

{join "",/<:Lu>/??"A".."Z"!!/<:Ll>/??"a".."z"!!$_}
\$\endgroup\$
1
\$\begingroup\$

PHP, 60 bytes

for(ctype_alpha($c=$argn)?$c=$c&a|A:$z=25;$z++<26;)echo$c++;

Run as pipe with -R.

\$\endgroup\$
1
\$\begingroup\$

Recursiva, 13 bytes

||&N(a(&N)a)a

Try it online!

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.

\$\endgroup\$
1
\$\begingroup\$

Ly, 32 bytes

"AZ"Ris~[p&o;]&p"az"Rl~[p&o;]lo;

Try it online!

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
\$\endgroup\$
1
\$\begingroup\$

Python 2, 73 bytes

c=ord(input())
print[chr(c),bytearray(range(c&96|1,c&96|27))][64<c&95<91]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog), 22 bytes

Unnamed prefix lambda.

{⊃a/⍨⍵∊¨a←⎕A(819⌶⎕A)⍵}

Try it online!

{} 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

\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog Unicode), 26 24 bytes

t←{⍵∊g←819⌶f←⎕A:g⋄⍵∊f:f⋄⍵}

Try it online!

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.
\$\endgroup\$
1
\$\begingroup\$

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).

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Is it possible to store the alphabet in a variable and use toupper in here (I don't know C) \$\endgroup\$ Nov 17, 2017 at 8:04
  • \$\begingroup\$ @StewieGriffin toupper only works on chars, and strtoupper/strupper is not standard C (nor implemented on many systems). \$\endgroup\$
    – MD XF
    Nov 17, 2017 at 16:53
1
\$\begingroup\$

Noether, 40 bytes

{0A~bI~a/~c}{bP}b{Ua/~d}{bUP}1{cd|-}{aP}

Try it online!

Uses Noether's built-in constant function A to return the string abcdefghijklmnopqrstuvwxyx.

\$\endgroup\$
1
\$\begingroup\$

R, 80 bytes

s=(r=65:90)+32
a=utf8ToInt(scan(,''));intToUtf8("if"(a%in%r,r,"if"(a%in%s,s,a)))

Try it online!

-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)))

Try it online!

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="")

Try it online!

\$\endgroup\$
1
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 50 bytes using grep \$\endgroup\$
    – roblogic
    Jan 28, 2023 at 11:16
  • 1
    \$\begingroup\$ Nice! Post that as a Zsh+coreutils answer if you want, I'll keep this as a pure Zsh answer. \$\endgroup\$ Jan 30, 2023 at 19:27
1
\$\begingroup\$

Python 3, 84 bytes

lambda x,a='abcdefghijklmnopqrstuvwxyz':[x,a,a.upper()][(x in a)+2*(x in a.upper())]

Try it online!

\$\endgroup\$

Your Answer

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

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