String operation in Java

I asked the following two questions in an interview yesterday

1 GT; Given a string, calculates a new string in which adjacent characters in the original string are separated by "*"

The example is as follows: the function name is public string pairstar (string STR)

pairStar("hello") → "hel*lo"     
 pairStar("xxyy") → "x*xy*y"          
 pairStar("aaaa") → "a*a*a*a"

2 – ; Given a string, calculates a new string in which all lowercase "X" characters have been moved to the end of the string

The example is as follows: the function name is public string endx (string STR)

endX("xxre") → "rexx"     
endX("xxhixx") → "hixxxx"     
endX("xhixhix") → "hihixxx"

I don't know how to complete the given problem and try to solve it

Solution

For 1), this is a very simple regular expression:

String in = "helllo goodbye";
  String out = in.replaceAll("(.)(?=\\1)","$1*");
  System.out.println(out);

Print:

hel*l*lo go*odbye

explain:

(.)     //match any one character into group 1
(?=\\1) //positive lookahead for that same character by backreferencing group 1

$1*     //replace that one character with the character followed by *

I may solve it later in 2), but I don't like to include multiple problems together

edit

Well, because I'm in the mood of a regular expression, here is 2):

String in = "xhixhix";
  String out = in;
  while (!out.matches("[^x]*x*")) {
     out = out.replaceAll("x(.*)","$1x");
  }
  System.out.println(out);

This replaces x (some) with (some) x until all x are at the end of the string I'm sure there's a better way to use / instead of regular expressions

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>