如何仅在String中的特定位置替换重复字符?

时间:2016-07-28 08:03:30

标签: java string

我有一个字符串:Hi / I / Jack /那里

在值之间包含多个'/'。并且这些值不是固定长度(可以是任何长度)

我需要用另一个字符串替换第二次出现的'/',这意味着输出应该是...... 高/ IamJack /有

我应该如何实现这一目标?尝试使用String.replace和一些逻辑,但它正在替换所有出现的地方,因为我只需要第二次更换。我只能使用String(不是StringBuilder或其他东西)

5 个答案:

答案 0 :(得分:4)

按字符串

中的每个元素计算/
    String s = "Hi/I/Jack/there";

    for(int i=0,count=0;i<s.length();i++)
    {
        if(s.charAt(i)=='/')// if the i'th element is '/'
        {
            count++;
            if(count==2)//it's second '/'
            {
                //separate to two part by second '/' and add what you want at middle
                s = s.substring(0,i) + "am" +s.substring(i+1,s.length());                    
            }
        }
    }

答案 1 :(得分:3)

想法:

  • 使用 int indexOf(String str,int fromIndex)找到第二个'/'的索引n
  • 使用该索引获取字符串的两个单独的子字符串,所以

    s.substring(0, n)将是"Hi/I"

    s.substring(n + 1)将为"Jack/there"

  • 通过连接"am/""Hi/I"之间添加"Jack/there"

    "Hi/I" + "am/" + "Jack/there"

<强>代码:

String s = "Hi/I/Jack/there";
int n = s.indexOf("/", s.indexOf("/") + 1); // index of the second '/'

String firstString = s.substring(0, n); // "Hi/I"
String lastString = s.substring(n + 1); // "Jack/there"`
String result = firstString + "am/" + lastString;

System.out.println(result);
// outputs Hi/Iam/Jack/there

答案 2 :(得分:1)

您可以拆分并加入字符串

String var ="Hi/I/Jack/there";
String [] arr = var.split("/");

并加入您想要的新字符串

答案 3 :(得分:1)

public class  S {
    public static void main(String[] args) {
        String s = "Hi/I/Jack/there";
            int index = s.indexOf("/", s.indexOf("/")+1); // find index of "/" starting after first "/"
            String result = s.substring(0, index) + "am" + s.substring(index+1);
            System.out.println(result);
    }
}

答案 4 :(得分:0)

也许有些像这样的外观正则表达式。

String[] tokens = "Hi/I/Jack/there".split("((?<=/)|(?=/))"); // split string to array [Hi, /, I, Am, Jack, /, there]                                                                                                                                                                                                                         
tokens[3] = "Am"; // second "/" will be always on 4th place, replace it with "Am"
System.out.println(String.join("", tokens)); // join again