加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java中的字符串操作问题

发布时间:2020-12-15 02:03:45 所属栏目:Java 来源:网络整理
导读:我昨天在接受采访时询问了以下2个问题 1 GT;给定一个字符串,计算一个新字符串,其中原始字符串中相邻的字符彼此之间用“*”分隔. 示例如下所示:: 函数名是public String pairStar(String str) pairStar("hello") → "hel*lo" pairStar("xxyy") → "x*xy*y" pa
我昨天在接受采访时询问了以下2个问题

1 GT;给定一个字符串,计算一个新字符串,其中原始字符串中相邻的字符彼此之间用“*”分隔.

示例如下所示::
函数名是public String pairStar(String str)

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

2 – ;给定一个字符串,计算一个新的字符串,其中所有小写的“x”字符都已移动到字符串的末尾.

示例如下所示::
?函数名是public String endX(String str)

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

我不知道如何完成给定的问题,并努力解决这个问题

解决方法

对于1),这是一个非常简单的正则表达方式:

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

打印:

hel*l*lo go*odbye

说明:

(.)     //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 *

我可能会在2)稍后解决,但我不喜欢将多个问题包含在一起.

编辑

好吧,因为我正处于一个正则表达式的心情,这里是2):

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

这将x(某些)替换为(某些)x,直到所有x都位于字符串的末尾.我敢肯定,有一种更好的方法可以使用/而不是正则表达式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读