开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜