38
\$\begingroup\$

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.

\$\endgroup\$
1
  • 19
    \$\begingroup\$ This is a very nice, simple-but-not-trivial challenge. \$\endgroup\$
    – user45941
    Commented Jul 9, 2016 at 1:45

46 Answers 46

1
2
2
\$\begingroup\$

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.

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

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

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

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

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

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.

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

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

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.

\$\endgroup\$
1
  • \$\begingroup\$ 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)}) \$\endgroup\$ Commented Aug 30, 2016 at 13:55
1
\$\begingroup\$

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.

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

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

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.

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

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.

\$\endgroup\$
2
  • \$\begingroup\$ 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. :) \$\endgroup\$
    – nicael
    Commented Apr 2, 2018 at 22:57
  • \$\begingroup\$ @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! \$\endgroup\$
    – Giuseppe
    Commented Apr 2, 2018 at 23:30
1
\$\begingroup\$

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!

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

Vyxal d, 5 bytes

ƛǍ[N"

Try it Online!

ƛ     # Map to...
 Ǎ[   # If alphabetical
   N" # Pair with swap_case
      # (Otherwise leave it)
      # (d flag) Print deep sum of stack
\$\endgroup\$
0
\$\begingroup\$

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);}}
\$\endgroup\$
6
  • 1
    \$\begingroup\$ This 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. \$\endgroup\$
    – nicael
    Commented Jul 10, 2016 at 16:23
  • \$\begingroup\$ @nicael , I edited. Is it OK ? \$\endgroup\$
    – Ever Think
    Commented Jul 10, 2016 at 17:07
  • \$\begingroup\$ I've removed other whitespace and newlines. \$\endgroup\$
    – nicael
    Commented Jul 10, 2016 at 17:26
  • 1
    \$\begingroup\$ Also, just a useful post :) \$\endgroup\$
    – nicael
    Commented Jul 10, 2016 at 17:27
  • 4
    \$\begingroup\$ @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. \$\endgroup\$
    – cat
    Commented Jul 11, 2016 at 0:15
0
\$\begingroup\$

x86-16 machine code, IBM PC DOS, 26 bytes

Binary:

00000000: b401 cd21 3c61 7c08 3c7a 7ff4 24df eb06  ...!<a|.<z..$...
00000010: 3c41 7cec 0c20 cd29 ebe6                 <A|.. .)..

Unassembled listing:

        START: 
B4 01       MOV  AH, 1                  ; DOS read char from STDIN 
CD 21       INT  21H                    ; read char into AL
3C 61       CMP  AL, 'a'                ; is letter < ASCII 'a'? 
7C 08       JL   UPPER                  ; if so, check if uppercase 
3C 7A       CMP  AL, 'z'                ; is letter > ASCII 'z'? 
7F F4       JG   START                  ; if so, don't repeat 
24 DF       AND  AL, NOT ('A' XOR 'a')  ; uppercase it 
EB 06       JMP  WRITE                  ; continue to display
        UPPER: 
3C 41       CMP  AL, 'A'                ; is letter < ASCII 'Z'? 
7C EC       JL   START                  ; if so, don't repeat either 
0C 20       OR   AL, 'A' XOR 'a'        ; lowercase it 
        WRITE: 
CD 29       INT  29H                    ; write AL to screen 
EB E6       JMP  START                  ; keep looping

Standalone IBM PC DOS executable. Input via STDIN, output to console.

I/O:

enter image description here

\$\endgroup\$
1
2

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.