40
\$\begingroup\$

In chat, we are often fast-typers and don't really look at the order of letters before posting a message. Since we are lazy, we need a program that automatically swaps the last two letters in our words, but since we don't want to respond too late, the code must be short.

Your task, if you wish to accept it, is to write a program that flips the last two letters of each word in a given string (so the word Thansk turns into Thanks). A word is a sequence of two or more letters in the English alphabet delimited by a single space.

  • The string / list of characters you receive as input is guaranteed to only contain alphabetic characters and spaces (ASCII [97 - 122], [65 - 90] and 32).

  • You can take input and provide output through any standard method, in any programming language, while taking note that these loopholes are forbidden by default.

  • The output may have one trailing space and / or one trailing newline.

  • The input will always contain words only (and the corresponding whitespace) and will consist of at least one word.

This is code-golf, so the shortest submission (scored in bytes), in each language wins!

Test cases

Note that the strings are surrounded with quotes for readability.

Input -> Output
"Thansk" -> "Thanks"
"Youer welcoem" -> "Youre welcome"
"This is an apple" -> "Thsi si na appel"
"Flippign Lettesr Aroudn" -> "Flipping Letters Around"
"tHe oDd chALlEneg wiht swappde lettesR" -> "teH odD chALlEnge with swapped letteRs"

Or, for test suite convenience, here are the inputs and their corresponding outputs separately:

Thansk
Youer welcoem
This is an apple
Flippign Lettesr Aroudn
tHe oDd chALlEneg wiht swappde lettesR
Thanks
Youre welcome
Thsi si na appel
Flipping Letters Around
teH odD chALlEnge with swapped letteRs

Thanks to DJMcMayhem for the title. This was originally a CMC.

asked Dec 27, 2017 at 19:45
\$\endgroup\$
6
  • \$\begingroup\$ May we output an array of words? \$\endgroup\$ Commented Dec 27, 2017 at 22:03
  • \$\begingroup\$ @Shaggy No, the output must be a string (or a list of characters by default) \$\endgroup\$ Commented Dec 27, 2017 at 22:04
  • \$\begingroup\$ May we request a trailing space on each input? \$\endgroup\$ Commented Dec 29, 2017 at 12:23
  • 1
    \$\begingroup\$ Whta shoudl eb doen wiht oen lettre worsd liek "a"? \$\endgroup\$ Commented Dec 29, 2017 at 14:08
  • 2
    \$\begingroup\$ @Fabian A word is a sequence of two or more letters \$\endgroup\$ Commented Dec 29, 2017 at 14:12

48 Answers 48

1
2
19
\$\begingroup\$

V, 4 (削除) 5 (削除ここまで) bytes

òeXp

Try it online!

|| denotes the cursor

The buffer starts with |w|ord and more words and the cursor being on the first character.

Recursively ò

go to the end of a word

wor|d| and more words

remove X the character to the left of the cursor

wo|d| and more words

paste it over the next character

wod|r| and more words

Implicit ending ò, repeat the same process for other words until the end of the buffer is reached

answered Dec 27, 2017 at 19:52
\$\endgroup\$
3
  • 2
    \$\begingroup\$ The right language for the task :) \$\endgroup\$ Commented Dec 27, 2017 at 22:52
  • \$\begingroup\$ Do you mean "Repeatedly" instead of "Recursively"? \$\endgroup\$ Commented Dec 30, 2017 at 15:09
  • \$\begingroup\$ @NieDzejkob The V wiki uses the word "recursively" to describe the ò command github.com/DJMcMayhem/V/wiki/Normal-Mode-Commands \$\endgroup\$ Commented Dec 30, 2017 at 18:06
12
\$\begingroup\$

Jelly, (削除) 7 (削除ここまで) 6 bytes

-1 with the May 2018 introduction of the quick (previously it was only available as the two-byte Ѐ).

Ḳ2œ?ⱮK

A monadic link taking and returning lists of characters

Try it online!

How?

Ḳ2œ?ⱮK - Link: list of characters
Ḳ - split at spaces
 2 - literal two
 Ɱ - map with:
 œ? - nth permutation (the 2nd permutation has the rightmost elements swapped)
 K - join with spaces
answered Dec 27, 2017 at 20:16
\$\endgroup\$
2
  • \$\begingroup\$ That's a nice abuse of permutations. Alternative \$\endgroup\$ Commented Dec 27, 2017 at 20:21
  • \$\begingroup\$ @Mr.Xcoder Ḳ2œ?ЀK also works and uses a single quick. \$\endgroup\$ Commented Dec 28, 2017 at 3:40
10
\$\begingroup\$

Brain-Flak, 122 bytes

{(({})[((((()()){}){}){}){}])((){[()](<{}>)}{}){{}<>(({}({}))[({}[{}])])(<>)}{}({}<>)<>}<>(({}({}))[({}[{}])]){({}<>)<>}<>

Try it online!

The worst language for the job :)

(削除) Readable (削除ここまで) Slightly more readable version:

{
 (({})[((((()()){}){}){}){}])((){[()](<{}>)}{})
 {
 {}
 <>
 (({}({}))[({}[{}])])
 (<>)
 }
 {}
 ({}<>)<>
}<>
(({}({}))[({}[{}])])
{
 ({}<>)
 <>
}<>
answered Dec 27, 2017 at 19:59
\$\endgroup\$
2
  • \$\begingroup\$ I can't believe this is longer than the Brainfuck version... \$\endgroup\$ Commented Dec 28, 2017 at 12:46
  • \$\begingroup\$ @pureferret Brain-flak tends to be longer than brainfuck. Mostly cause it requires two bytes per primitive command, where brain-flak requires two. \$\endgroup\$ Commented Dec 28, 2017 at 13:21
8
\$\begingroup\$

Python 3, 50 bytes

print(*(w[:-2]+w[:-3:-1]for w in input().split()))

Try it online!

This answer abuses Python 3's behavior of print: Multiple arguments are printed with a single space between them. Of course, we can't just give it multiple arguments because we don't know how many words will be in the input. So we use the splat operator. Basically

print(*[a,b,c])

is exactly the same thing as

print(a,b,c)

Abusing that makes a full program turn out shorter than a function/lambda where we'd have to use ' '.join or something similar.

answered Dec 27, 2017 at 19:47
\$\endgroup\$
1
  • \$\begingroup\$ Looks like Python 2 saves 2 bytes by writing for w in input().split():print w[:-2]+w[:-3:-1],. In Python 3, extracting the last two characters would work well with print(*(''.join(a)+c+b for*a,b,c in input().split())) except that a needs to be remade into a string. \$\endgroup\$ Commented Dec 28, 2017 at 4:01
8
\$\begingroup\$

Haskell, 40 bytes

(f=<<).words
f[a,b]=b:a:" "
f(x:r)=x:f r

Try it online! Usage example: (f=<<).words $ "abc xyz" yields "acb xzy ".

answered Dec 27, 2017 at 20:49
\$\endgroup\$
1
  • \$\begingroup\$ So you're telling me the shortest approach is both the approaches combined? >_< \$\endgroup\$ Commented Dec 27, 2017 at 21:16
8
\$\begingroup\$

Retina, 13 bytes

(.)(.)\b
2ドル1ドル

Try it online! Link includes test cases.

answered Dec 27, 2017 at 23:27
\$\endgroup\$
6
\$\begingroup\$

Matlab (R2016b), (削除) 51 (削除ここまで) 50 bytes

Saved (削除) 49 (削除ここまで) 50 (!) bytes thanks to @Giuseppe.

function s(a),regexprep(a,'(\w)(\w)( |$)','2ドル1ドル ')

And my previous answer:

Matlab (R2016b), 100 bytes

(Just for the fun of it :P)

function s(a),a=regexp(a,' ','split');for i=1:length(a),fprintf('%s ',a{i}([1:end-2 end end-1])),end

Explanation:

function s(a) % Defining as a function...
a=regexp(a,' ','split'); % Splits the input string at the spaces
for i=1:length(a) % Loops through each word
 fprintf('%s ',a{i}([1:end-2 end end-1])) % And prints everything with the last two characters swapped.
end
answered Dec 27, 2017 at 20:14
\$\endgroup\$
6
  • 1
    \$\begingroup\$ one character words can't happen, as a word is defined to be at least two characters. \$\endgroup\$ Commented Dec 27, 2017 at 20:30
  • \$\begingroup\$ would regexprep work here? Something like regexprep(a,'(\w*)(\w)(\w)','1円3円2円')? \$\endgroup\$ Commented Dec 27, 2017 at 20:53
  • \$\begingroup\$ D= This. Was. Epic! I think you should post this answer, since it's totally different from mine. The only thing is that Matlab references the matches with 1ドル, and not 1円, so it would be regexprep(a,'(\w*)(\w)(\w)','1ドル3ドル2ドル'). \$\endgroup\$ Commented Dec 27, 2017 at 20:59
  • 1
    \$\begingroup\$ you should post it as a separate answer / in this answer; it's always good to see if a regex would help or not on a string challenge! Besides, I clearly don't understand MATLAB's regex engine, so it wouldn't quite be fair for me to take credit for it. \$\endgroup\$ Commented Dec 27, 2017 at 21:02
  • 1
    \$\begingroup\$ function s(a),regexprep(a,'(\w)(\w)( |$)','2ドル1ドル ') is still another byte shorter! \$\endgroup\$ Commented Dec 27, 2017 at 23:30
6
\$\begingroup\$

C, (削除) 62 (削除ここまで) (削除) 58 (削除ここまで) 54 bytes

Thanks to @Dennis for saving (削除) four (削除ここまで) eight bytes!

f(char*s){s[1]>32||(*s^=s[-1]^=*s^=s[-1]);*++s&&f(s);}

Try it online!

answered Dec 27, 2017 at 19:59
\$\endgroup\$
4
  • \$\begingroup\$ ah, the xor-based swap \$\endgroup\$ Commented Dec 29, 2017 at 14:52
  • \$\begingroup\$ How is s[-1] safe? I get how it works in the recursive runs (at the end after *++s), but on the first pass shouldn't it be undefined behavior? \$\endgroup\$ Commented Apr 6, 2022 at 1:48
  • \$\begingroup\$ 53 bytes \$\endgroup\$ Commented Aug 22 at 15:52
  • \$\begingroup\$ 49 bytes clang \$\endgroup\$ Commented Aug 22 at 15:55
5
\$\begingroup\$

Prolog (SWI), 60 bytes

[A,B]+[B,A].
[A,B,32|U]+[B,A,32|Y]:-U+Y,!.
[A|U]+[A|Y]:-U+Y.

Try it online!

Explanation

First we define the base case:

p([A,B],[B,A]).

This means that the last two letters will always be swapped.

Then we define what happens if we are right next to a space:

p([A,B,32|U],[B,A,32|Y]):-p(U,Y),!.

Two strings match if right before a space the letters before the space are swapped and the remainder if the strings match. We then use ! to cut.

Our last case is if we are not next to a space the first two letters need to match.

p([A|U],[A|Y]):-p(U,Y).
answered Dec 27, 2017 at 20:22
\$\endgroup\$
5
\$\begingroup\$

Wolfram Language, 117 bytes

StringReplace[RegularExpression["\\b[[:alpha:]]{2,}\\b"]:>StringDrop[StringInsert["0ドル",StringTake["0ドル",{-1}],-3],-1]]

Try it online!

Applied to the test strings.

StringReplace[
 RegularExpression["\\b[[:alpha:]]{2,}\\b"] :> 
 StringDrop[StringInsert["0ドル", StringTake["0ドル", {-1}], -3], -1]] /@
 {"Thansk", "Youer welcoem", "This is an apple", 
 "Flippign Lettesr Aroudn", "tHe oDd chALlEneg wiht swappde lettesR"} // Column
Thanks
Youre welcome
Thsi si na appel
Flipping Letters Around
teH odD chALlEnge with swapped letteRs
user202729
17.6k2 gold badges39 silver badges71 bronze badges
answered Dec 27, 2017 at 20:59
\$\endgroup\$
1
  • 4
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ Commented Dec 27, 2017 at 21:06
5
\$\begingroup\$

R, (削除) 111 (削除ここまで) (削除) 51 (削除ここまで) 41 bytes

Courtesy of @Giuseppe, a regex approach which blows my old method out of the water.

cat(gsub("(.)(.)\\b",'\2円\1円',scan(,"")))
answered Dec 27, 2017 at 20:41
\$\endgroup\$
5
  • 1
    \$\begingroup\$ regex are much more efficient here: Try it online! \$\endgroup\$ Commented Dec 27, 2017 at 20:48
  • \$\begingroup\$ (not that I don't appreciate the guts it takes to do a pure string manipulation approach in R) \$\endgroup\$ Commented Dec 27, 2017 at 20:50
  • \$\begingroup\$ 84 byte golf of your approach \$\endgroup\$ Commented Dec 27, 2017 at 23:22
  • \$\begingroup\$ @Giuseppe Wow, nice work! I've edited them into my answer, although if you'd prefer to make your own answer please go ahead! \$\endgroup\$ Commented Dec 28, 2017 at 1:10
  • 1
    \$\begingroup\$ nah, don't worry about it. I golfed down another 10 bytes: porting another regex approach, and a 70 byte of your old approach \$\endgroup\$ Commented Dec 28, 2017 at 15:14
5
\$\begingroup\$

J, (削除) 20 19 (削除ここまで) 11 bytes

Credit to @Bolce Bussiere

1&A.&.>&.;:

Try it online!

 &.;: on words
 &.> on each
 A. apply the permutation
1& number 1, swap the last two elements
answered Dec 27, 2017 at 22:02
\$\endgroup\$
3
  • 1
    \$\begingroup\$ 13 Bytes with (1&A.&.>)&.;: \$\endgroup\$ Commented Dec 31, 2017 at 19:24
  • \$\begingroup\$ @BolceBussiere perfect \$\endgroup\$ Commented Jan 1, 2018 at 18:27
  • \$\begingroup\$ Could you add an explanation? Wondering if I can port it to K to reduce the embarrassing byte count of my solution! \$\endgroup\$ Commented Jan 1, 2018 at 21:18
5
\$\begingroup\$

APL (Dyalog Classic), 28 bytes

1↓∊(( ̄2↓⊢),2↑⌽) ̈' '(,⊂⍨⊣=,)⍞

⎕ML and ⎕IO are both 1,

Try it online!

Explanation

  • ... (,⊂⍨⊣=,) ... Split (while keeping borders, and appending a border to the beginning) ...
  • ... ⍞ ... the input ...
  • ... ' ' ... ... at spaces.
  • ... ( ... ) ̈ ... Then, to each element of that:
    • ... , ... Concatenate ...
    • ... ( ̄2↓⊢) ... ... every item except the last two ...
    • ... 2↑⌽ ... ... with the reverse of the last two elements.
  • 1↓∊ ... Finally, return all but the first element of the flattened result.
answered Dec 28, 2017 at 14:54
\$\endgroup\$
1
  • \$\begingroup\$ return all but the first \$\endgroup\$ Commented Feb 1, 2018 at 11:18
4
\$\begingroup\$

Funky, 34 bytes

s=>s::gsub("(.)(.)( |$)","2ドル1ドル3ドル")

Try it online!

answered Dec 27, 2017 at 20:04
\$\endgroup\$
4
\$\begingroup\$

Haskell, 45 bytes

-2 bytes thanks to H.PWiz.

(r.g.r=<<).words
g(x:y:z)=' ':y:x:z
r=reverse

Try it online!

answered Dec 27, 2017 at 19:52
\$\endgroup\$
0
4
\$\begingroup\$

Alice, 24 bytes

/0RR'.%1ドル\' o
\ix*o ne@/

Try it online!

Explanation

/...\' o
\.../

This forms a loop where the loop body is a linear Ordinal snippet and we execute ' o in Cardinal mode between every two loop iterations. The latter just prints a space.

Unfolding the zigzag structure of the Ordinal code, the linear loop body actually looks like this:

iR*' %e10xRo.n$@

Breaking this down:

i Read all input. On subsequent iterations, this will push an empty string.
R Reverse.
* Join. On the first iteration, this joins the input to an implicit empty string,
 which does nothing. On subsequent iterations, it will join the empty string to
 the word on top of the string, thereby getting rid of the empty string.
' % Split around spaces. On the first iteration, this will split the input
 into individual words. On subsequent iterations, this does nothing.
e10 Push "10".
x Use this to permute the (reversed) word on top of the stack. In
 particular, the word is rearranged with the same permutation that is
 required to sort the string "10", which means the first two letters
 get swapped (which correspond to the last two letters of the actual
 word).
R Reverse the swapped word.
o Print it.
.n$@ If there are no words left on the stack, terminate the program.
answered Jan 3, 2018 at 13:42
\$\endgroup\$
1
  • \$\begingroup\$ Just noticed that the letter swap can be done in three bytes (h~Z) instead of four (e10x), but I'm not seeing a way to adjust the layout to actually save a byte overall with that. \$\endgroup\$ Commented Jan 3, 2018 at 13:52
3
\$\begingroup\$

brainfuck, (削除) 109 (削除ここまで) 100 bytes

Edit: don’t have to handle one letter words

,[>++++[-<-------->],]>+[-<[>++++[<++++++++>-]<[->>+<<]<]<<[->>+<<]>[[-<+>]>]<<[>+>+>]-<]>>>>>>>[.>]

Try it online!

Prints a trailing space

How It Works

,[>++++[-<-------->],] Puts input on the tape and subtracts 32 from each character
 This separates each word
>+[- Start the loop
 <[>++++[<++++++++>-]<[->>+<<]<] Add 32 to each letter of the word
 Skip this on the first iteration for the last word
 <<[->>+<<]>[[-<+>]>] Swaps the last two letters of the word
 <<[>+>+>]- If there is another word to the left continue loop
 Also set up to add a space to the end of the word
 <] End loop
 >>>>>>>[.>] Print the modified string

Previous version, 109 bytes

,[>++++[-<-------->],]>+[-<[>++++[<++++++++>-]<[->>+<<]<]<<[[->>+<<]>[[-<+>]>]<<[<]]>[>]<[>+>+>]-<]>>>>>>[.>]

Try it online!

answered Dec 28, 2017 at 2:47
\$\endgroup\$
3
\$\begingroup\$

QuadR, 8 bytes

..\b
⌽⍵M

Try it online!

answered Dec 29, 2017 at 2:42
\$\endgroup\$
3
\$\begingroup\$

Google Sheets, 33 Bytes

Anonymous worksheet function that takes input from cell A1 and outputs to the calling cell

=RegExReplace(A1,"(.)(.)\b","2ドル1ドル

-2 Bytes Thanks to @KevinCruijssen for the use of (.) over (\w)

answered Jan 3, 2018 at 13:10
\$\endgroup\$
2
  • \$\begingroup\$ Both (\w) can be golfed to (.) if I'm not mistaken. The \b is already an indication to look for words only. (Not entirely sure though, but it works in Java.) \$\endgroup\$ Commented Feb 1, 2018 at 10:54
  • \$\begingroup\$ @KevinCruijssen - You are absolutely correct, it can be. Thank you! \$\endgroup\$ Commented Feb 1, 2018 at 17:52
3
\$\begingroup\$

Julia 1.0, 30 bytes

!s=replace(s,r"..\b"=>reverse)

Try it online!

detect end of words with a regex r"..\b" and apply reverse on the matches

answered Jul 23, 2021 at 12:29
\$\endgroup\$
3
\$\begingroup\$

Curry, 33 bytes

Tested in both KiCS2 and PAKCS.

f(u++[x,y])=u++[y,x]
(>>=f).words

Curry's powerful patterns let it beat the Haskell answer!

To test it you can use Smap. Just select KiCS2 2.2.0 or PAKCS 2.2.0 and paste the following complete code:

f(u++[x,y])=u++[y,x]
g=(>>=f).words
main=f "Hello world an happy day"
answered Apr 5, 2022 at 13:17
\$\endgroup\$
2
\$\begingroup\$

sed, (削除) 20 (削除ここまで) 17+1 (-r) = 18 bytes

s/(.)(.)\b/2円1円/g

Try it online!

answered Dec 28, 2017 at 0:18
\$\endgroup\$
4
  • \$\begingroup\$ The TIO link does not match your posted code. The TIO link is a few bytes longer. \$\endgroup\$ Commented Dec 28, 2017 at 3:06
  • \$\begingroup\$ Whoops, fixed the link \$\endgroup\$ Commented Dec 28, 2017 at 3:14
  • \$\begingroup\$ You can remove |$. It's not doing anything. (For it to do what you expect you'd need (.)(.)(\b|$), but that's not necessary because \b already matches the end of the string.) \$\endgroup\$ Commented Dec 28, 2017 at 19:42
  • \$\begingroup\$ Whoops, meant to get rid of that. Thanks, \$\endgroup\$ Commented Dec 28, 2017 at 19:58
1
\$\begingroup\$

Perl 5, 19 + 1 (-p) = 20 bytes

s/(\w)(\w)\b/2ドル1ドル/g

Try it online!

answered Dec 27, 2017 at 20:41
\$\endgroup\$
1
  • \$\begingroup\$ Nice solution! Came up with very similar (but using -040). You can use (.) instead of (\w) as the input will only ever have letters to save 2. If using -040 you can also reaplace \b with $ and, using ; instead of /, drop /g: Try it online! \$\endgroup\$ Commented Jul 15, 2021 at 11:10
1
\$\begingroup\$

PHP, (削除) 119 (削除ここまで) 107 bytes

Edit: thanks to totallyhuman

<?php foreach(explode(" ",trim(fgets(STDIN)))as$w)echo substr($w,0,strlen($w)-2).strrev(substr($w,-2))," ";

Try it online!

answered Dec 27, 2017 at 23:15
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Can't you make $word a single character variable name? \$\endgroup\$ Commented Dec 28, 2017 at 0:33
  • \$\begingroup\$ @totallyhuman Yup! I wrote the full version and then compressed it, but didn't notice that. Thanks you. \$\endgroup\$ Commented Dec 28, 2017 at 3:33
  • \$\begingroup\$ PHP open tags can be omitted in the answer saving you 6 bytes. \$\endgroup\$ Commented Dec 28, 2017 at 12:26
  • \$\begingroup\$ I wonder if fgets(STDIN) can be omitted or replaced by $x too, like not all answers do count the input to their answers \$\endgroup\$ Commented Dec 28, 2017 at 12:32
  • \$\begingroup\$ trim() should be unnecessary. \$\endgroup\$ Commented Dec 29, 2017 at 8:55
1
\$\begingroup\$

Haskell, 41 bytes

foldr(%)" "
a%(b:' ':r)=b:a:' ':r
a%s=a:s

Try it online!

Outputs with a trailing space.

The repeated ' ':r looks wasteful. But a%(b:t@(' ':r))=b:a:t is the same length and a%(b:t)|' ':_<-t=b:a:t is one byte longer.


Haskell, 41 bytes

f(a:b:t)|t<"A"=b:a:f t|1>0=a:f(b:t)
f e=e

Try it online!

answered Dec 28, 2017 at 3:37
\$\endgroup\$
1
\$\begingroup\$

Haskell, (削除) 53 (削除ここまで) 45 bytes

u[a,b]=[b,a]
u(a:b)=a:u b
unwords.map u.words

Try it online!

Explanation

u is a function that swaps the last two letters of a word. To apply it to all the words we use words to split the list, map it across all of the words and then use unwords to put it back together.

answered Dec 27, 2017 at 19:47
\$\endgroup\$
4
  • \$\begingroup\$ You seem to have included the f= from TIO in your byte count, even though it's not included in your answer here. \$\endgroup\$ Commented Dec 27, 2017 at 23:55
  • \$\begingroup\$ How do you pass the input to your program? Does main=print$f"Hello World" not count to the program? \$\endgroup\$ Commented Dec 28, 2017 at 12:27
  • \$\begingroup\$ @Kritzefitz Thanks! I've adjusted it. \$\endgroup\$ Commented Dec 28, 2017 at 18:26
  • \$\begingroup\$ @DanFromGermany My program makes a point-free function unwords.map u.words. You call it like any other Haskell function. main=print$f"Hello World" does not count because my submission is a function and not a program. \$\endgroup\$ Commented Dec 28, 2017 at 18:28
1
\$\begingroup\$

Clean, (削除) 75 (削除ここまで) 59 bytes

-16 from Laikoni

@[a,b]=[b,a]
@[a,b,' ':c]=[b,a,' ': @c]
@[a:b]=[a: @b]
@e=e

Try it online!

answered Dec 27, 2017 at 21:37
\$\endgroup\$
2
  • \$\begingroup\$ This seems to work fine without import StdEnv. \$\endgroup\$ Commented Dec 28, 2017 at 13:28
  • \$\begingroup\$ Also moving @[]=[] to the bottom and replacing it by @e=e saves two more bytes: Try it online! \$\endgroup\$ Commented Dec 28, 2017 at 13:32
1
\$\begingroup\$

PHP, 65 bytes

requires PHP 7.1 (or later)

for(;$s=$argv[++$i];$s[-1]=$s[-2],$s[-2]=$c,print"$s ")$c=$s[-1];

takes sentence as separate command line arguments. Run with -nr.


working on a single string, 77+1 bytes:

foreach(explode(" ",$argn)as$s){$c=$s[-1];$s[-1]=$s[-2];$s[-2]=$c;echo"$s ";}

Run as pipe with -nR.


... or try them online.

answered Dec 29, 2017 at 8:57
\$\endgroup\$
1
\$\begingroup\$

Java 8, 35 bytes

s->s.replaceAll("(.)(.)\\b","2ドル1ドル")

Port of @TaylorScott's Google Sheets answer, after I golfed two bytes. EDIT: I see it's now a port of Neil's Retina answer after my two golfed bytes.

Explanation:

Try it online.

s-> // Method with String as both parameter and return-type
 s.replaceAll("(.)(.) // Replace any two characters,
 \\b", // with a word-boundary after it (space or end of String)
 "2ドル1ドル") // With the two characters swapped
answered Feb 1, 2018 at 10:59
\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), (削除) 38 (削除ここまで) (削除) 36 (削除ここまで) 32 bytes

(削除) s=>s.replace(/(.)(.)( |$)/g,"2ドル1ドル ") (削除ここまで)
s=>s.replace(/(.)(.)\b/g,"2ドル1ドル")

Try it online!

RegExp approach courtesy @Giuseppe (although I thought of this independently), assuming words separated by only one space

-2 for only considering 1 space and add trailing space

-4 Thanks @Shaggy

answered Dec 28, 2017 at 9:38
\$\endgroup\$
7
  • \$\begingroup\$ Doesn't matter if there are more spaces, I think \$\endgroup\$ Commented Dec 28, 2017 at 9:48
  • \$\begingroup\$ @l4m2 But if there are more spaces then it will become a 38 for s=>s.replace(/(.)(.)( +|$)/g,"2ドル1ドル3ドル"). \$\endgroup\$ Commented Dec 28, 2017 at 9:49
  • \$\begingroup\$ @l4m2 BTW my original answer was s=>s.replace(/(.)(.)(\s|$)/g,"2ドル1ドル3ドル") \$\endgroup\$ Commented Dec 28, 2017 at 9:51
  • \$\begingroup\$ ab abc abcd abcde abcdef does ab_, bc_, cd_, de_, ___, ef_, ___ \$\endgroup\$ Commented Dec 28, 2017 at 9:55
  • 1
    \$\begingroup\$ F=s=>s.replace(/(.)(.)(?!\w)/g,"2ドル1ドル") same length \$\endgroup\$ Commented Dec 28, 2017 at 10:08
1
2

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.