Swap letters in a string

前端 未结 4 792
我寻月下人不归
我寻月下人不归 2021-01-12 12:59

I need to swap letters in a string with the following rules:

  • A is replaced by T
  • T is replaced by A
  • C is replaced by G
  • G is replaced
4条回答
  •  不要未来只要你来
    2021-01-12 13:43

    I would go for a more general solution like this:

    public String tr(String original, String trFrom, String trTo) {
      StringBuilder sb = new StringBuilder();
    
      for (int i = 0; i < original.length(); ++i) {
        int charIndex = trFrom.indexOf(original.charAt(i));
        if (charIndex >= 0) {
          sb.append(trTo.charAt(charIndex));
        } else {
          sb.append(original.charAt(i));
        }
      }
    
      return sb.toString(); 
    }
    

    Calling the function like this would give the result you need:

    tr("ACGTA", "ATCG", "TAGC")
    

    So the function is pretty much the same as unix tr utility:

    echo ACGTA | tr ATCG TAGC
    

提交回复
热议问题