【问题标题】:how to replace a char in a specific index with another char on another index [duplicate]如何用另一个索引上的另一个字符替换特定索引中的字符[重复]
【发布时间】:2018-07-18 19:27:22
【问题描述】:

以下代码打印eleelde,但我希望它打印elcaalde

我该怎么做? index() 是否有类似替换字符的功能??

我想将i=0 处的字符分配给i=6 处的字符值并打印单词elcaalde

public class ReverseExperiments3 {  
   public static void main (String[] args) {
      String s= "alcaalde";
      s=s.replace('a','e'); 
      System.out.println(s);
   }
}

【问题讨论】:

    标签: java str-replace


    【解决方案1】:

    在char数组中改一下:

    char[] cs = s.toCharArray();
    cs[0] = cs[6];  // For example.
    s = new String(cs);
    

    【讨论】:

    • 为了达到结果,它是第7个元素,所以s[7]。不管怎样,你按照他的要求给它 s[6] 是对的
    【解决方案2】:

    试试这个代码:如果你想得到你想要的,它是第 7 个元素

    String s= "alcaalde";
    char[] cs = s.toCharArray();
    cs[0] = cs[7];  
    s = new String(cs);
    

    【讨论】:

      【解决方案3】:

      您也可以在这里使用正则表达式替换:

      String s = "alcaalde";
      s = s.replaceFirst("(.)(.{6})(.)", "$3$2$1");
      

      Demo

      @andy 给出的答案可能是这个确切问题的最佳答案。但是如果 OP 需要移动 strings,那么基于正则表达式的方法将使我们处于一个相当好的位置。

      【讨论】:

      • 为什么是replaceAll,而不是replaceFirst
      • @khelwood 在这种特殊情况下,由于模式覆盖了整个字符串,我希望 replaceFirstreplaceAll 基本上做同样的事情。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 2022-12-22
      • 2018-07-05
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多