ケースの複製と切り替え


34

目標は、文字列を入力として、各ラテン文字を複製し、大文字と小文字を切り替えます(つまり、大文字が小文字に、またはその逆になります)。

入力と出力の例:

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|@!

入力は、印刷可能なASCIIシンボルで構成されます。

非ラテン文字、数字、特殊文字を複製しないでください。


17
これは非常に素晴らしく、簡単ですが、些細なことではありません。
メゴ

回答:



17

Python、56 54バイト

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

Ideoneでテストします。


ダン!アウトは4バイト...で私にgolfed
R.ガプス

これは、文字以外の文字をどのように維持しますか?空の文字列として表示されると思います。
アトラロジスト

@atlasologist Ideoneでわかるように、彼らはそうではありません。*の優先度はの場合よりも高い+ためc、スワップされた場合のみに影響します。
デニス

ああ、大丈夫、私はそのように考えていませんでした。いいね
アトラロジスト

16

JavaScriptのES6、70 68 66 64バイト

@Kevin Lauのおかげで2バイト節約されました-ケニーではありません

@CᴏɴᴏʀO'Bʀɪᴇɴのおかげで2バイト節約

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

説明

これは本当にハッキーです:

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

使用されていないもの:

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

基本的l < "a"に、文字のコードポイントがコードポイントよりも小さいかどうかをチェックしますa(したがって、大文字になります)。もしそうなら、to + Low + erCaseどちらl['toLowerCase']()になり、文字を小文字にします。`引用符は文字列の書式設定を許可するため、基本的には次のことを考えることができます

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

as:"to" + (l<"a" ? "Low" : "Upp") + "erCase"呼び出す関数を生成します(文字列を大文字または小文字にします)。これを角かっこ[ ... ]で囲み、名前が文字列として指定されたプロパティにアクセスできるようにします。これは適切な関数を返し、それを呼び出すだけです。


3
/[A-Z]/gi短い正規表現です:3
バリューインク

@ KevinLau-notKenny素敵なキャッチ、ありがとう!
ダウンゴート

1
to${l<"a"?"Lower":"Upper"}Caseto${l<"a"?"Low":"Upp"}erCase
コナー・オブライエン

@CᴏɴᴏʀO'Bʀɪᴇɴいいね、ありがとう!
ダウンゴート

4
l[`to${l<"a"?"Low":"Upp"}erCase`]()悪についての新しい定義があると思います。
-gcampbell

10

ルビー、37 33(30 + -pフラグ)バイト

swapcase救助へ!並べ替え。@Lynnから-4バイト。

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

gsub(/[a-z]/i){$&+$&.swapcase}プラスpフラグは31バイトです。
リン

1
@Lynnコンセンサスはデフォルトのスクリプトとの編集の違いが必要だったと思うので、pフラグは(space)-p別名3バイトです。
値のインク

8

C、63 60バイト

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

'a' XOR 32 == 'A'などの事実を使用します

FryAmTheEggmanのおかげで3バイト節約されました。


s++最後に移動してputchar&&putchar(32^*s++)1バイト
ジャコモガラベロ

私はあなたが交換することができると思う&&*、あなたすることはできませんか、?
aloisdgは復活モニカ言う

1
&&短絡動作がどのように機能するかを考えると、これらの両方が機能しないと確信しています。
リン

f(char*s){isalpha(putchar(*s))&&putchar(32^*s);*s&&f(1+s);}再帰的?
l4m2

1
f(char*s){*s&&f(1+s,isalpha(putchar(*s))&&putchar(32^*s));}再帰的?
l4m2

6

CJam、11バイト

l_el_eu.+.|

ここでテストしてください。

説明

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



5

Haskell、73バイト

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

5

チェダー118 104バイト

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

最初の本当のチェダーの答え!!! これは私が思っていたよりもはるかにクライマックスです...; _;

リリース1.0.0-beta.9、非競合で動作します。


あなたが言うことができるように、私はゴルフ用にチェダーを設計していませんでした:/

ゴルフをしていない:

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

使用法:

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

更新: 2016年7月14日3項が完成し、これが84バイトになりました

チェダー、84バイト

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

バージョンv1.0.0-beta.14以降で動作します


4
わーい!私たちは長い間この瞬間を待っていました!
DJMcMayhem

1つまたは2つのメソッド名を変更すると、有効なSidef
cat

@cat o_o類似性は不安定です
-Downgoat

まあ、どちらもPerl、Perl 6、Ruby、Pythonなどの影響を受けているので、それほど驚くことではありません:P
cat

1
@catああ、いや、いや、いや、いや、チェダーはPythonの影響を受けませんでした
Downgoat

4

網膜、28 27 21バイト

これらはタブであり、スペースではありません。

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

オンラインで試す

皆の提案をありがとう。


The spaces are eaten by SE.
Conor O'Brien

[A-Za-z] -> i`[A-Z]
Downgoat

Martin and I were talking in chat, and we came up with: retina.tryitonline.net/…
FryAmTheEggman

@FryAmTheEggman Ah, I forgot about _. I'm going to use tabs so I can test all test cases at once, though.
mbomb007

1
But 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

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

Can you provide a way to try it online?
aloisdg says Reinstate Monica

@aloisdg Try ideone.com
cat

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'

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

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

3
By 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

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

1
Instead 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

1
Oh, one more: [x]++ is x:.
nimi

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'

You still need to use /i or your regexp will match several codepoints between letters.
Oleg V. Volkov

@OlegV.Volkov oh right, thanks, answer edited.
Dada

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

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.


Matching with // and then using $`[-1] is clever.
Jordan

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

Cool! That looks one byte shorter to me.
histocrat

Er, yes, one byte. I think I had some extra code in there to test that I accidentally counted.
Jordan

There is no need to use the self-modifying version of .swapcase!. (I mean, remove the !.)
manatwork

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

98 bytes -- maybe sometime next year, we can find another golf of this, hahaha.
Giuseppe

1
I 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

@MickyT thanks, fixed now.
rturnbull

@MickyT scan will work with input given wrapped in quotes (as is often the case for command-line arguments in other languages)
Giuseppe

@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

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!


Maybe you could provide a link to the interpreter?
nicael

2
@nicael It IS linked... It's right there on github.
mbomb007

So no online interpreter? :(
nicael

@nicael Then download it, and run it. There doesn't have to be an online interpreter, just an interpreter.
mbomb007

1
@nicael Yeah, there is no online interpreter available yet :(. The offline version should work though.
Adnan



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

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

3

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

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

I imagine you can save a byte by using $" instead of ' ', but I haven't tested.
msh210

@msh210, nice! How could I forget to check perlvar for default strings? Thanks!
Oleg V. Volkov

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.

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

@recursive Thanks! Forgot about that one :/ Will edit in soon.
Khuldraeseth na'Barya

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

@WeijunZhou Thanks, fixed!
Khuldraeseth na'Barya

2

Python, 59 bytes

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

Edited to fix repeating non-alphabetic characters



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^' ':'';


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"
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.