【问题标题】:Replace strings populated in an ArrayList<String> with other values将 ArrayList<String> 中填充的字符串替换为其他值
【发布时间】:2016-10-05 11:26:41
【问题描述】:

我目前正在做一个项目,我需要检查某个字符串的数组列表,如果满足该条件,请将其替换为新字符串。 我只会展示相关代码,但基本上之前发生的事情是读入一个长字符串,分成三个一组,然后这些字符串填充一个数组。我需要在数组中查找并替换这些值,然后将它们打印出来。这是填充数组列表的方法:

private static ArrayList<String> splitText(String text)
{
    ArrayList<String> DNAsplit = new ArrayList<String>();
    for (int i = 0; i < text.length(); i += 3) 
    { 
        DNAsplit.add(text.substring(i, Math.min(i + 3, text.length()))); 
    }
    return DNAsplit;
}

如何在这个数组列表中搜索多个字符串(这是一个示例 aminoAcids = aminoAcids.replaceAll ("TAT", "Y");),然后将新值打印出来。 非常感谢任何帮助。

【问题讨论】:

  • 您的splitText 方法过于复杂。只需使用for (int i = 0; i &lt; text.length(); i += 3) { DNAsplit.add(text.substring(i, Math.min(i + 3, text.length()))); }。
  • 我在这段代码中的任何地方都没有看到数组是我遗漏了什么还是你的意思是数组列表?
  • @AndyTurner 谢谢你的修改,干净多了。

标签: java arrays methods replace


【解决方案1】:

在 Java 8 中

list.replaceAll(s-> s.replace("TAT", "Y"));

【讨论】:

  • 谢谢,这正是我要找的。​​span>
【解决方案2】:

为什么不创建一个具有键值的哈希图并在加载时使用它来填充此列表,而不是稍后对其进行修改?

Map<String,String> dnaMap = new HashMap<String,String>() ;
dnaMap.push("X","XXX");
.
.
.
dnaMap.push("Z","ZZZ");

并像下面这样使用它:

            //Use the hash map to lookup the temp key 
    temp= text.substring(i, Math.min(i + 3, text.length())); 
            DNAsplit.add(dnaMap.get(temp));

【讨论】:

    【解决方案3】:

    列表中没有这样的“全部替换”方法。您需要按元素应用替换;与对单个字符串执行此操作的唯一区别是您需要将值从列表中取出,并将新值设置回列表中:

    ListIterator<String> it = DNAsplit.listIterator();
    while (it.hasNext()) {
      // Get from the list.
      String current = it.next();
    
      // Apply the transformation.
      String newValue = current.replace("TAT", "Y");
    
      // Set back into the list.
      it.set(newValue);
    }
    

    如果你想打印出新值:

    System.out.println(DNAsplit);
    

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 2014-02-28
      • 2021-11-02
      • 2013-11-19
      • 2021-07-12
      • 2011-07-25
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多