Duplicate & switch case

34

3

The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB     
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!

The input consists of printable ASCII symbols.

You shouldn't duplicate non-latin letters, numbers, special chars.

nicael

Posted 2016-07-08T20:15:41.873

Reputation: 4 585

17This is a very nice, simple-but-not-trivial challenge. – Mego – 2016-07-09T01:45:38.703

Answers

10

Jelly, 5 bytes

żŒsQ€

Try it online!

How it works

żŒsQ€  Main link. Argument: s (string)

 Œs    Yield s with swapped case.
ż      Zip s with the result.
   Q€  Unique each; deduplicate each pair of characters.

Dennis

Posted 2016-07-08T20:15:41.873

Reputation: 196 637

17

Python, 56 54 bytes

lambda s:''.join(c+c.swapcase()*c.isalpha()for c in s)

Test it on Ideone.

Dennis

Posted 2016-07-08T20:15:41.873

Reputation: 196 637

Dang! Out golfed me by 4 bytes... – R. Kap – 2016-07-08T20:57:18.857

How does this maintain the non-letter characters? I'd think they'd show up as empty strings. – atlasologist – 2016-07-08T21:21:01.937

@atlasologist As you can see on Ideone, they do not. * has higher precedence than +, so it only affects the c with swapped case. – Dennis – 2016-07-08T21:22:40.757

Ohh, okay, I didn't think of it like that. Nice. – atlasologist – 2016-07-08T21:24:53.940

16

JavaScript ES6, 70 68 66 64 bytes

Saved 2 bytes thanks to @Kevin Lau - not Kenny

Saved 2 bytes thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ

s=>s.replace(/[A-Z]/gi,l=>l+l[`to${l<"a"?"Low":"Upp"}erCase`]())

Explanation

This uses a really hacky:

l[`to${l<"a"?"Low":"Upp"}erCase`]()

which ungolfed is:

l[`to${
   l < "a" ?
   "Low" : 
   "Upp"
}erCase`]()

Basically l < "a" checks if the code point of the letter is less then the code point of a (therefore being an uppercase letter). If it is it'll do to + Low + erCase which becomed l['toLowerCase']() and makes the character lowercase. ` quotes allow string formatting so essentially you can think of:

`to${l < "a" ?"Low" : "Upp"}erCase`

as: "to" + (l<"a" ? "Low" : "Upp") + "erCase" which generates the function to call (make the string upper or lower case). We put this in square brackets [ ... ] which lets us access a property given its name as a string. This returns the appropriate function and then we just call it.

Downgoat

Posted 2016-07-08T20:15:41.873

Reputation: 27 116

3/[A-Z]/gi is a shorter regex :3 – Value Ink – 2016-07-08T20:28:02.570

@KevinLau-notKenny oh nice catch, thanks! – Downgoat – 2016-07-08T20:29:30.980

1to${l<"a"?"Lower":"Upper"}Case to to${l<"a"?"Low":"Upp"}erCase – Conor O'Brien – 2016-07-08T21:14:25.967

@CᴏɴᴏʀO'Bʀɪᴇɴ oh nice, thanks! – Downgoat – 2016-07-08T21:38:07.213

4l[`to${l<"a"?"Low":"Upp"}erCase`]() I think we have a new definition of evil. – gcampbell – 2016-07-09T11:53:49.350

That toUpperCase() trick is really clever. +1 – Cyoce – 2016-08-29T23:22:57.723

10

Ruby, 37 33 (30 + -p flag) bytes

swapcase to the rescue! Sort of. -4 bytes from @Lynn.

gsub(/[a-z]/i){$&+$&.swapcase}

Value Ink

Posted 2016-07-08T20:15:41.873

Reputation: 10 608

gsub(/[a-z]/i){$&+$&.swapcase} plus the p flag is 31 bytes. – Lynn – 2016-07-08T22:54:26.490

1@Lynn I believe consensus was edit difference needed from default script, so the p flag is (space)-p aka 3 bytes. – Value Ink – 2016-07-08T23:16:06.743

8

C, 63 60 bytes

f(char*s){for(;*s;s++)isalpha(putchar(*s))&&putchar(32^*s);}

Uses the fact that 'a' XOR 32 == 'A', etc.

Three bytes saved thanks to FryAmTheEggman.

Lynn

Posted 2016-07-08T20:15:41.873

Reputation: 55 648

you can move the s++ in the last putchar (&&putchar(32^*s++)) to save one byte

– Giacomo Garabello – 2016-07-11T13:43:48.697

I think you can replace && with *, can't you? – aloisdg moving to codidact.com – 2016-07-16T18:13:56.893

1I’m pretty sure both of those don’t work, if I think about how &&’s short-circuiting behaviour works. – Lynn – 2016-07-16T20:13:06.547

f(char*s){isalpha(putchar(*s))&&putchar(32^*s);*s&&f(1+s);} recursive? – l4m2 – 2018-03-19T04:23:05.327

1f(char*s){*s&&f(1+s,isalpha(putchar(*s))&&putchar(32^*s));} recursive? – l4m2 – 2018-03-24T06:29:49.947

6

CJam, 11 bytes

l_el_eu.+.|

Test it here.

Explanation

l      e# Read input.
_el    e# Duplicate, convert to lower case.
_eu    e# Duplicate, convert to upper case.
.+     e# Concatenate the two characters in matching positions from those two
       e# strings. E.g. "ab!" "AB!" would give ["aA" "bB" "!!"].
       e# For each character from the original string and the corresponding 
.|     e# string from this list, take the set union (which eliminates duplicates
       e# and keeps the order the values appear in from left to right, so that
       e# the original case of each letter comes first).

Martin Ender

Posted 2016-07-08T20:15:41.873

Reputation: 184 808

5

Pyth, 7 bytes

sm{+dr2

Test suite.

sm{+dr2    input: Q
sm{+dr2dQ  implicit arguments

        Q  input
 m         for each character as d:
     r2d       swapcase
   +d          prepend d
  {            deduplicate
s          join as string

Leaky Nun

Posted 2016-07-08T20:15:41.873

Reputation: 45 011

Haha, that's really fast :D – nicael – 2016-07-08T20:18:02.623

5

Python 3.5, 60 56 bytes:

for i in input():print(end=i+i.swapcase()[:i.isalpha()])

A full program. Will try to golf more.

Try It Online! (Ideone)

R. Kap

Posted 2016-07-08T20:15:41.873

Reputation: 4 730

5

Haskell, 73 bytes

l=['a'..'z']
u=['A'..]
(>>= \c->c:maybe""pure(lookup c$zip l u++zip u l))

Lynn

Posted 2016-07-08T20:15:41.873

Reputation: 55 648

5

Cheddar, 118 104 bytes

(s)->s.chars.map((i)->{if String.letters has i.lower{if i<"a"{i+i.lower}else{i+i.upper}}else{i}}).join()

First real Cheddar answer!!! This is a lot less climactic than I thought it would be... ;_;

Works with release 1.0.0-beta.9, non-competing.


As you can tell I didn't design cheddar to be golfy :/

Ungolfed:

(str) -> str.chars.map(
    (i) -> {
        if String.letters has i {
            if i < "a" { // Check char code, meaning it's upper case if true
                i+i.lower
            }
            else {
                i+i.upper
            }
        } else {
            i
        }
    }
).join()

Usage:

var doThing = <code here>;
doThing("input...");

Update: 7/14/16 I've finished ternaries making this come down to 84 bytes

Cheddar, 84 bytes

(s)->s.chars.map((i)->String.letters has i.lower?i<"a"?i+i.lower:i+i.upper:i).join()

works as of version v1.0.0-beta.14

Downgoat

Posted 2016-07-08T20:15:41.873

Reputation: 27 116

4Yay! We've been waiting for this moment for a long time! – James – 2016-07-10T18:39:09.750

With one or two method name changes, is also valid Sidef

– cat – 2016-07-10T21:11:19.353

@cat o_o the similarity is unsettling – Downgoat – 2016-07-10T21:13:32.883

Well, they're both influenced by Perl, Perl 6, Ruby, Python, etc, so it's not that surprising :P – cat – 2016-07-10T21:32:50.333

1@cat oh no no no no no, cheddar was not influenced by python – Downgoat – 2016-07-10T21:33:28.643

@Downgoat xD I meant JavaScript because Sidef wasn't influenced (much) by Python either -- more coffee pls – cat – 2016-07-10T21:42:37.400

@Downgoat ewwwww python. Also I love these lambdas with implicit returns – Cyoce – 2016-08-29T23:33:51.177

4

Retina, 28 27 21 bytes

Those are tabs, not spaces.

.
$&  $&
T`lL    p`Ll_`  .

Try it online

Thanks for the suggestions everyone.

mbomb007

Posted 2016-07-08T20:15:41.873

Reputation: 21 944

The spaces are eaten by SE. – Conor O'Brien – 2016-07-08T20:25:57.377

[A-Za-z] -> i\[A-Z]` – Downgoat – 2016-07-08T20:36:06.513

Martin and I were talking in chat, and we came up with: http://retina.tryitonline.net/#code=LgokJsK2JCYKVGBsTMK2cGBMbF9gwrYu&input=YmEgZDEhenp6

– FryAmTheEggman – 2016-07-08T20:41:10.110

@FryAmTheEggman Ah, I forgot about _. I'm going to use tabs so I can test all test cases at once, though. – mbomb007 – 2016-07-08T20:45:41.857

You can build a test suite by using per-line mode and a group! http://retina.tryitonline.net/#code=JShHYAouCiQmwrYkJgpUYGxMwrZwYExsX2DCti4&input=YmFkCk5pY2UKVCBlIFMgdApzIEUgdAoxITEhMXN0IQpuMDBiIAooZS5nLikKSDNsfEAh

– FryAmTheEggman – 2016-07-08T20:50:25.127

@FryAmTheEggman Sure, but it's not golfed. :P – mbomb007 – 2016-07-08T21:30:12.060

1But the test suite doesn't have to be golfed :P Just leaving a note saying "the first line makes it run separately on each line" is usually good enough. Here, it would save you the craziness of tab characters. – FryAmTheEggman – 2016-07-08T21:44:48.313

@FryAmTheEggman I'm on Team Tabs. Sorry. – mbomb007 – 2016-07-08T21:47:36.627

4

C, 87 80

Pass a string as input to f() and the output is written to STDOUT. The string is not modified.

f(char*v){for(;*v;++v)putchar(*v),isalpha(*v)?putchar(*v-32+64*!islower(*v)):0;}

owacoder

Posted 2016-07-08T20:15:41.873

Reputation: 1 556

Can you provide a way to try it online? – aloisdg moving to codidact.com – 2016-07-09T13:58:18.367

@aloisdg Try http://ideone.com

– cat – 2016-07-10T01:52:05.323

4

sed, 30 bytes

29 bytes code + 1 byte parameter -r

s/([a-z])|([A-Z])/&\u\1\l\2/g

Usage:

echo -e 'bad\nNice\nT e S t\ns E t\n1!1!1st!\nn00b\n(e.g.)\nH3l|@!' |\
sed -r 's/([a-z])|([A-Z])/&\u\1\l\2/g'

Marco

Posted 2016-07-08T20:15:41.873

Reputation: 581

4

Ruby, 31+1=32 30+1=31 bytes

With the -p flag, run

gsub(/(?<=(.))/){$1.swapcase!}

Takes advantage of the fact that swapcase! will return nil on anything but an ASCII letter, which translates to an empty string when returned out of the gsub block. @Jordan saved a byte by capturing the previous character in a look-behind.

histocrat

Posted 2016-07-08T20:15:41.873

Reputation: 20 600

Matching with // and then using $`[-1] is clever. – Jordan – 2016-08-29T14:55:13.757

1I managed to shave off six bytes with lookbehind: gsub(/(?<=(.))/){$1.swapcase!}. Same basic concept, though, so feel free to use it. – Jordan – 2016-08-29T15:13:06.340

Cool! That looks one byte shorter to me. – histocrat – 2016-08-29T15:58:50.057

Er, yes, one byte. I think I had some extra code in there to test that I accidentally counted. – Jordan – 2016-08-29T16:08:39.443

There is no need to use the self-modifying version of .swapcase!. (I mean, remove the !.) – manatwork – 2016-08-29T16:19:24.690

No, that part's still necessary to avoid duplicating non-alphabet characters. – histocrat – 2016-08-29T17:00:08.113

4

J, 31 29 bytes

[:;]<@~."1@,.tolower,.toupper

Explanation

[:;]<@~."1@,.tolower,.toupper  Input: s
                      toupper  Convert s to all uppercase
             tolower           Convert s to all lowercase
                    ,.         Join them as columns in a 2d array
   ]                           Identity function, get s
           ,.                  Prepend s as a column to the 2d array
      ~."1@                    Take the unique chars on each row
    <@                         Box them
[:;                            Unbox the list of boxes and join their contents and return

miles

Posted 2016-07-08T20:15:41.873

Reputation: 15 654

4

Haskell, 121, 101, 85, 82

import Data.Char
g n|isLower n=toUpper n|1<2=toLower n
(>>= \x->x:[g x|isAlpha x])

Zylviij

Posted 2016-07-08T20:15:41.873

Reputation: 390

3By replacing the if-then-else by guards, you can save 15 bytes or so. And isLower is shorter than the construct with elem, for 5 bytes more. – arjanen – 2016-07-09T06:00:33.940

1>>= is concatMap (or concat.map) with arguments flipped: f n = n >>= (\x->if isAlpha x then[x,r x]else[x]). You can go pointfree and omit the function name and replace the definition of f with (>>= \x->if isAlpha x then[x,r x]else[x]). – nimi – 2016-07-09T18:40:54.160

1Instead of otherwise you can use any expression that evaluates to True, e.g. 1<2. You can replace the if .. then .. else with a list comprehension: \x->[x]++[g x|isAlpha x]. Oh, and there's a bug: the second toUpper in g must be a toLower. – nimi – 2016-07-11T16:36:14.463

1Oh, one more: [x]++ is x:. – nimi – 2016-07-11T17:57:43.657

4

Perl, 36 bytes (35 + -n flag)

s/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige

(-p tag needed)

(-2 bytes thanks to @Dom Hasting)

Short explanation:
ord returns the numeric value of a char. ord(any lower case) >= 97, and ord(any upper case) <= 90).

Run with :

perl -pe 's/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige'

Dada

Posted 2016-07-08T20:15:41.873

Reputation: 8 279

You still need to use /i or your regexp will match several codepoints between letters. – Oleg V. Volkov – 2016-07-12T00:14:21.473

@OlegV.Volkov oh right, thanks, answer edited. – Dada – 2016-07-12T10:31:25.907

Got it down one more byte, using your method: Try it online!

– Xcali – 2018-04-03T03:20:27.497

4

R, 191 187 168 156 98 99 bytes

99 bytes due to improvements fro Giuseppe and MickyT.

paste0(x<-unlist(strsplit(readline(),"")),gsub("[^A-Za-z]","",chartr("a-zA-Z","A-Za-z",x)),collapse="")

rturnbull

Posted 2016-07-08T20:15:41.873

Reputation: 3 689

98 bytes -- maybe sometime next year, we can find another golf of this, hahaha. – Giuseppe – 2018-03-23T19:54:53.960

1I hate to be the bearer of bad new, but it fails on test cases with spaces. readline() can be used, but it will cost a byte – MickyT – 2018-04-02T23:15:36.673

@MickyT thanks, fixed now. – rturnbull – 2018-04-02T23:28:47.707

@MickyT scan will work with input given wrapped in quotes (as is often the case for command-line arguments in other languages) – Giuseppe – 2018-04-03T00:46:05.970

@Giuseppe Sorry I didn't realise that. I just thought it automatically split on whitespace unless you specify a non whitespace character. Sorry rturnbull – MickyT – 2018-04-03T07:03:13.010

3

Stax, 7 6 bytes

Thanks to @recursive for a byte saved!

┤§ÆP♦■

Run and debug it at staxlang.xyz! (link is to unpacked version)

Unpacked (7 bytes):

c:~\{um

Explanation:

c:~\{um
c          Copy the top element of the stack (the input, in this case).
 :~        Switch case of each letter in the copy.
   \       Zip. This produces an array of two-character strings.
    { m    Map a block over this array of two-character strings.
     u       Get all unique elements.
           Implicit concatenate and print.

Khuldraeseth na'Barya

Posted 2016-07-08T20:15:41.873

Reputation: 2 608

Thanks for giving stax a try. One easy improvement you can make is to use u instead of :g. It will get all the unique elements in an array, which is exactly what you want in this case. Other than that, this looks well golfed. – recursive – 2018-03-28T22:29:08.877

@recursive Thanks! Forgot about that one :/ Will edit in soon. – Khuldraeseth na'Barya – 2018-03-29T04:29:44.567

Doesn't work for 123. You may need to change the format for all inputs (i.e. quote them). The link is also broken. You need to replace m=11 with m=2. There is a PPCG post generating button on staxlang.xyz so you may want to use that one. – Weijun Zhou – 2018-04-02T23:21:53.090

@WeijunZhou Thanks, fixed! – Khuldraeseth na'Barya – 2018-04-03T00:48:06.003

3

05AB1E, 7 bytes

Code:

vyyš«Ù?

Explanation:

v       # For each in input.
 yyš    # Push y and y swapcased.
    «Ù  # Concatentate and uniquify.
      ? # Print without a newline.

Uses the CP-1252 encoding. Try it online!

Adnan

Posted 2016-07-08T20:15:41.873

Reputation: 41 965

Maybe you could provide a link to the interpreter? – nicael – 2016-07-08T20:39:32.233

2@nicael It IS linked... It's right there on github. – mbomb007 – 2016-07-08T20:39:45.610

So no online interpreter? :( – nicael – 2016-07-08T20:42:44.110

@nicael Then download it, and run it. There doesn't have to be an online interpreter, just an interpreter. – mbomb007 – 2016-07-08T20:42:45.373

1@nicael Yeah, there is no online interpreter available yet :(. The offline version should work though. – Adnan – 2016-07-08T20:42:57.147

@mbo I'm not saying it doesn't, I was just wondering if there is one. Neither I was implying that the off-line interpreters are bad. – nicael – 2016-07-08T20:45:25.720

3

Pyke, 8 6 bytes

FDl4+}

Try it here!

Blue

Posted 2016-07-08T20:15:41.873

Reputation: 26 661

3

V, 21 bytes

Try it online!

Too many bytes...

Ó./°ò
Íá/°°
Îlg~lÎHògJ

James

Posted 2016-07-08T20:15:41.873

Reputation: 54 537

3

Actually, 8 bytes

`;Öo╔`MΣ

Try it online!

Explanation:

`;Öo╔`MΣ
`;Öo╔`M   for each character in input:
 ;          duplicate the character
  Ö         swap case
   o        append to original character
    ╔       remove duplicated characters
       Σ  concatenate

Mego

Posted 2016-07-08T20:15:41.873

Reputation: 32 998

3

MATL, 11 9 bytes

tYov"@uv!

Try it Online

Explanation

        % Implicitly grab input as string
t       % Duplicate the input
Yo      % Swap case of all characters
v       % Vertically concatenate the original and swap-cased versions
"       % For each column (letter in the original)
  @u    % Compute the unique values (without sorting)
  v!    % Vertically concatenate with the existing output and transpose
        % Implicit end of for loop and implicit display

Suever

Posted 2016-07-08T20:15:41.873

Reputation: 10 257

3

Perl, 28 22 21 bytes (20 + -p flag)

s/[a-z]/$&.$&^$"/ige

Oleg V. Volkov

Posted 2016-07-08T20:15:41.873

Reputation: 171

I imagine you can save a byte by using $" instead of ' ', but I haven't tested. – msh210 – 2016-07-14T22:11:32.850

@msh210, nice! How could I forget to check perlvar for default strings? Thanks! – Oleg V. Volkov – 2016-07-15T11:08:08.527

2

T-SQL, 244

The byte total includes a one-byte string. Replace the example input string "Q" with the string you want to try.

DECLARE @I VARCHAR(MAX)='Q',@O VARCHAR(MAX)='',@ CHAR #:SELECT @=LEFT(@I,1),@O+=@+CASE WHEN @ LIKE'[A-Za-z]'COLLATE Thai_BIN THEN CASE WHEN ASCII(@)/13IN(5,6)THEN LOWER(@)ELSE UPPER(@)END ELSE''END,@I=STUFF(@I,1,1,'')IF LEN(@I)>0GOTO # PRINT @O

This script works in SQL Server 2008 R2, although you can try it in SQL Server 2016 here. This SQL works by iterating through the characters in the input string @I, checking each character using a short-named collation and ASCII codes. When one character is processed, the result is added to the output string @O and removed from @I.

Muqo

Posted 2016-07-08T20:15:41.873

Reputation: 499

2

Japt v2.0a0, 8 bytes

r\lÈ+c^H

Try it


Explanation

r            :Replace
 \l          :Regex /[a-z]/gi
   È         :Pass each match X through a function
    +        :  Append
    c        :  The charcode of X
     ^       :  Bitwise XORed
       H     :  With 32

Shaggy

Posted 2016-07-08T20:15:41.873

Reputation: 24 623

2

str, 6 bytes

d#S:#q

Try it online!

Explanation

d#S:#q
          over each character:
d         duplicate
 #S       swapcase
   :      concatenate
    #q    uniq-ify string

Conor O'Brien

Posted 2016-07-08T20:15:41.873

Reputation: 36 228

2

Python, 59 bytes

lambda s:''.join((x,x+x.swapcase())[x.isalpha()]for x in s)

Edited to fix repeating non-alphabetic characters

atlasologist

Posted 2016-07-08T20:15:41.873

Reputation: 2 945

2

Julia, 40 bytes

!s=[print(c,isalpha(c)?c$' ':"")for c=s]

Try it online!

Dennis

Posted 2016-07-08T20:15:41.873

Reputation: 196 637

not s is (list comprehension) okay, Julia... – cat – 2016-07-10T00:36:30.927

2

C#, 82 71 bytes

s=>string.Concat(s.Select(c=>c+(char.IsLetter(c)?(char)(c^32)+"":"")));

C# lambda where the input and the output are string. Try it online.

11 bytes thanks to @Lynn trick.

aloisdg moving to codidact.com

Posted 2016-07-08T20:15:41.873

Reputation: 1 767

2

PHP 4.1, 57 bytes

This code assumes access through a web server (Apache, for example), using the default configuration.

You can pass the string by sending the key S by any means (POST, GET, COOKIE, SESSION...).

<?for($i=0;$c=$S[$i++];)echo$c,ctype_alpha($c)?$c^' ':'';

Ismael Miguel

Posted 2016-07-08T20:15:41.873

Reputation: 6 797

2

Common Lisp (Lispworks), 262 bytes

(defun f(s)(let((b""))(dotimes(i(length s))(if(lower-case-p(elt s i))(progn #1=(setf b(concatenate 'string b(string #2=(elt s i))))(setf b(concatenate 'string b(string(char-upcase #2#)))))(progn #1#(setf b(concatenate 'string b(string(char-downcase #2#)))))))b))

ungolfed:

(defun f (s)
  (let ((b ""))
    (dotimes (i (length s))
      (if (lower-case-p (elt s i))
          (progn
           #1=(setf b (concatenate 'string b (string #2=(elt s i))))
           (setf b (concatenate 'string b (string (char-upcase #2#)))))
        (progn
          #1#
          (setf b (concatenate 'string b (string (char-downcase #2#)))))))
    b))

Usage:

CL-USER 1 > (f "abc")
"aAbBcC"

CL-USER 2 > (f "bad")
"bBaAdD"

sadfaf

Posted 2016-07-08T20:15:41.873

Reputation: 101

2

Java 8, 105 104 80 bytes

a->{for(char c:a)System.out.print(c+(c>64&c<91|c>96&c<123?(char)(c^32)+"":""));}

Explanation:

Try it here.

a->{                          // Method with character-array parameter and no return-type
  for(char c:a)               //  For each character in the input:
    System.out.print(c        //   Print the current character
     +(c>64&c<91|c>96&c<123?  //   And if it's a letter:
       (char)(c^32)+""        //    Print the letter again with reversed case
      :                       //   Else:
       ""));}                 //    Print nothing more

Kevin Cruijssen

Posted 2016-07-08T20:15:41.873

Reputation: 67 575

1

Rust, 250 bytes

fn main(){let(mut i,mut o)=(String::new(),String::new());std::io::stdin().read_line(&mut i);let b:&[u8]=i.trim().as_bytes();for x in b{o.push(*x as char);if*x>64&&*x<91{o.push((x+32)as char)}else if*x>96&&*x<123{o.push((x-32)as char)}}print!("{}",o)}

Ungolfed

fn main() {
    let (mut input_string, mut output_string) = (String::new(), String::new());
    std::io::stdin().read_line(&mut input_string);
    let bytes: &[u8] = input_string.trim().as_bytes();

    for x in bytes {
        output_string.push(*x as char);
        if *x > 64 && *x < 91 {
            //is_uppercase
            output_string.push((x + 32) as char);
        } else if *x > 96 && *x < 123 {
            //is_lowercase
            output_string.push((x - 32) as char);
        }
    }
    print!("{}", output_string);
}

This answer assumes the input only consists of ASCII characters. It uses comparisons and addition/subtraction instead of library functions as it is shorter.

dragonite44

Posted 2016-07-08T20:15:41.873

Reputation: 91

1

Add++, 100 bytes

D,g,@,O91 65r$e
D,l,@,O123 97r$eBn
D,w,@~,S
D,f,@~,€gB]VAbU€lB]GBcB+32€*B]VAbU€OB]GBcB+€CJABc€wB@B+J

Try it online!

This is annoyingly long. Let's compare this answer to the current shortest, Dennis' Jelly answer:

żŒsQ€

Here, I've split it into three parts: ż, Œs and Q€, highlighted to show the corresponding parts in the Add++ code, as so:

D,g,@,O91 65r$e
D,l,@,O123 97r$eBn
D,w,@~,S
D,f,@~,€gB]VAbU€lB]GBcB+32€*B]VAbU€OB]GBcB+€CJABc€wB@B+J

How it works

		; A note on functions:
		; Each function returns the value on the top of the stack
		; A function has 'flags' that change its behaviour:
		;
		;	@	-	Specifies an argument to be taken
		;	~	-	Splats the arguments to the stack

D,u,@,		; Declare a monadic function 'u'
		; Example argument:	['I']
	O	; Ordinal;	STACK = [73]
	91 65r	; [65 ... 90];	STACK = [73 [65 66 ... 89 90]]
	$e	; Contains?	STACK = [1]

D,l,@,		; Declare a monadic function 'l'
		; Example argument:	['i']
	O	; Ordinal;	STACK = [105]
	123 97r	; [97 ... 122];	STACK = [105 [97 98 ... 121 122]]
	$e	; Contains?	STACK = [1]
	Bn	; Negate;	STACK = [-1]

D,w,@~,		; Declare a monadic function 'w'
		; Example argument:	[['N' 'n']]
	S	; Deduplicate;	STACK = [['N' 'n']]

D,f,@~,		; Declare a monadic function 'f'
		; Example argument:		['N' 'i' 'c' 'e' '!']
	€u	; Map 'u' over €ach;	STACK = [1 0 0 0 0]
	B]	; Wrap the stack;	STACK = [[1 0 0 0 0]]
	V	; Save;			STACK = []
	AbU	; Push argument;	STACK = ['N' 'i' 'c' 'e' '!']
	€l	; Map 'l' over €ach;	STACK = [0 -1 -1 -1 0]
	B]	; Wrap;			STACK = [[0 -1 -1 -1 0]]
	G	; Retrieve;		STACK = [[0 -1 -1 -1 0] [1 0 0 0 0]]
	BcB+	; Column sums;		STACK = [1 -1 -1 -1 0]
	32€*	; Multiply €ach by 32;	STACK = [32 -32 -32 -32 0]
	B]	; Wrap;			STACK = [[32 -32 -32 -32 0]]
	V	; Save;			STACK = []
	AbU€OB]	; Codepoints of input;	STACK = [[78 105 99 101 33]]
	G	; Retrieve;		STACK = [[78 105 99 101 33] [32 -32 -32 -32 0]]
	BcB+	; Column sums;		STACK = [110 73 67 69 33]
	€C	; Convert to chars;	STACK = ['n' 'I' 'C' 'E' '!']
	JABc	; Zip with argument;	STACK = [['n' 'N'] ['I' 'i'] ['C' 'c'] ['E' 'e'] ['!' '!']]
	€w	; Map 'w' over €ach;	STACK = [['n' 'N'] ['I' 'i'] ['C' 'c'] ['E' 'e'] ['!']]
	B@	; Reverse each;		STACK = [['N' 'n'] ['i' 'I'] ['c' 'C'] ['e' 'E'] ['!']]
	B+	; Sum each;		STACK = ['Nn' 'iI' 'cC' 'eE' '!']
	J	; Join;			STACK = ['NniIcCeE!']

caird coinheringaahing

Posted 2016-07-08T20:15:41.873

Reputation: 13 702

1

Kotlin, 87 86 bytes

x->x.map{c->if(c.isLetter())"$c${(c.toInt()xor 32).toChar()}" else c}.joinToString("")

Try it online!

I wish Kotlin had a ternary operator, but it doesn't so I'm stuck with the more verbose if/else.

I feel like I can get this shorter if I can find a way to consolidate map{} and joinToString() in one call.

Makotosan

Posted 2016-07-08T20:15:41.873

Reputation: 503

1

SNOBOL4 (CSNOBOL4), 139 bytes

	U =&UCASE
	L =&LCASE
	I =INPUT
S	I LEN(1) . X REM . I	:F(O)
	X ANY(L U)	:S(D)F(A)
D	X =X REPLACE(X,L U,U L)
A	O =O X	:(S)
O	OUTPUT =O
END	

Try it online!

The line X ANY(L U) :S(D)F(A) checks if any of X are Upper or Lowercase, going to D if so or to A if not. Then D duplicates and swaps case, and A concatenates the results together, finally outputting once I has no characters.

Giuseppe

Posted 2016-07-08T20:15:41.873

Reputation: 21 077

Looks like this challenge is still getting some attention and I am not sure how to revive it since there're already really short answers which are difficult to outgolf. :) – nicael – 2018-04-02T22:57:15.353

@nicael there are always more languages! This is a really good challenge, and I've taken the perspective that code golf is trying to find the shortest answer in each language! – Giuseppe – 2018-04-02T23:30:32.983

1

C, 62 bytes

Function that reads from stdin and writes to stdout:

f(c){while(c=getchar())printf(isalpha(c)?"%c%c":"%c",c,c^32);}

Stefano Sanfilippo

Posted 2016-07-08T20:15:41.873

Reputation: 1 059

1

Erlang, 106 bytes

f(S)->G=string,lists:flatten([case G:to_upper(C)==G:to_lower(C)of true->C;false->[C,C bxor 32]end||C<-S]).

Uses Lynn's XOR trick to toggle the case.

c.P.u1

Posted 2016-07-08T20:15:41.873

Reputation: 1 049

1

Gema, 37 characters

<J>=$1@upcase{$1}
<K>=$1@downcase{$1}

Sample run:

bash-4.3$ gema '<J>=$1@upcase{$1};<K>=$1@downcase{$1}' <<< 'H3l|@!'
Hh3lL|@!

manatwork

Posted 2016-07-08T20:15:41.873

Reputation: 17 865

1

PowerShell, 102 Bytes

-join([char[]]$args[0]|%{$_;if($_-cmatch'[A-Z]'){"$_".ToLower()}if($_-cmatch'[a-z]'){"$_".ToUpper()}})

Run the script with an argument like so:

PS C:\PretendDirectory> .\DupeCase.ps1 "Hello World ?!!1"
HheElLlLoO WwoOrRlLdD ?!!1

Ungolfed:

-join([char[]]$args[0] | % {
    $_
    if($_-cmatch'[A-Z]'){
        "$_".ToLower()
    }
    if($_-cmatch'[a-z]'){
        "$_".ToUpper()
    }
})

Explanation:

This script splits the argument from a string into a character array, and loops through the array. It returns a given character then, if it's an upper case letter between A and Z returns a lowercase version using the built in function, does the same for lowercase letters. To wrap up it joins the array into a single string.

Chirishman

Posted 2016-07-08T20:15:41.873

Reputation: 389

If you go with v3 or higher for the -in operator, you can exploit the fact that char and int can implicitly cast back and forth and use string multiplication instead of ifs to cut it down to 88 -- -join([char[]]$args[0]|%{$_;"$_".ToLower()*($_-in65..90)+"$_".ToUpper()*($_-in97..122)}) – AdmBorkBork – 2016-08-30T13:55:38.683

0

Yabasic, 133 bytes

A answer that takes input as a raw string and outputs to the STDOUT.

Line Input""S$
For i=1To Len(S$)
c$=Mid$(S$,i,1)
u$=Upper$(c$)
?c$;
If"@"<u$And u$<"["Then
If c$=u$Then?Lower$(c$);Else?u$;Fi
Fi
Next

Try it online!

Taylor Scott

Posted 2016-07-08T20:15:41.873

Reputation: 6 709

0

Java, 259 bytes

for (i=0;i<in.length();i++)
{
if(Character.isLowerCase(in.charAt(i))){
o=o+in.charAt(i)+Character.toUpperCase(in.charAt(i));}
else if(Character.isUpperCase(in.charAt(i))){o=o+in.charAt(i)+Character.toLowerCase(in.charAt(i));}
else {o=o+in.charAt(i);}}

Ragesh D Antony

Posted 2016-07-08T20:15:41.873

Reputation: 101

1This is the code golf, your answer should be as short as possible (and defintely lack any excess spacing, tabbing, etc). Also you should include the length of your code in bytes. – nicael – 2016-07-10T16:23:40.773

@nicael , I edited. Is it OK ? – Ragesh D Antony – 2016-07-10T17:07:37.930

I've removed other whitespace and newlines. – nicael – 2016-07-10T17:26:41.977

1

Also, just a useful post :)

– nicael – 2016-07-10T17:27:57.070

4@nicael Unlike Stack Overflow and other SE sites, please don't edit others' answers, even if you are the OP. it's up to them. – cat – 2016-07-11T00:15:10.477

@cat Okay, sorry for that! I have edited not because of being the question OP, but just because wanted to help the new user. – nicael – 2016-07-11T17:26:50.237