开发者

How do I reverse the order of two words in a string?

开发者 https://www.devze.com 2023-01-06 15:54 出处:网络
I have a string like this: $a = \"Mike , Tree \"; I want to reverse it开发者_StackOverflow to \"Tree, Mike\".

I have a string like this:

$a = "Mike , Tree "; 

I want to reverse it开发者_StackOverflow to "Tree, Mike".

Is there any function to do that?


Split the string into two strings, flip them, and rejoin them.

Or, use a regex:

$a =~ s/(.+),(.+)/\2,\1/g;


Use the reverse function:

$reversed = join(",", reverse split(",", $string));


If you are guaranteed the your string that you want to be reversed will be separated by commas then I would split the string at the comma and then go through the array it produces from the length of it to 0 and append it to an empty string.


Just for your problem.

$a =~ s/([A-Za-z]+)([^A-Za-z]+)([A-Za-z]+)/$3$2$1/;

[JJ@JJ trunk]$ perl -E '$a = "Mike , Tree "; $a =~ s/([A-Za-z]+)([^A-Za-z]+)([A-Za-z]+)/$3$2$1/; say $a;'
Tree , Mike
0

精彩评论

暂无评论...
验证码 换一张
取 消