用Java替换字符串中某个子字符串的数字

时间:2018-08-28 18:52:40

标签: string replace

我目前正在努力尝试提取字符串的某个子字符串并替换其内容。准确的数字。数字改变了,所以我不能接受整个字符串。例如,我有一条类似

的消息
String message = "hi John. You have two contracts listed: 
                  TV-70002548 and FV-50006578. The first contract 
                  ends on March 15th. I will pay you a final amount of 350 $."

在该字符串中,我有一组不同的数字,但我只想提取合同编号并进行重写,例如TV-70002548-> TV-seven null null null two five four eight

我写了一种提取V-之后的所有数字的方法,因为该字符对于字符串中的合同编号是唯一的:

   private String replaceContractNo(String pMessage, String pInput, String pOutput) {
        String contractno;
        contractno = pMessage.substring(pMessage.indexOf("V-")-2);
        return contractno.replaceAll(pInput, pOutput);
    }

稍后我想用单词替换数字,例如:

replaceContractNo(pMainMessage,"0"," null")
replaceContractNo(pMainMessage,"1"," one")

这不起作用,因为每次都会写出该消息。有解决这个问题的简便方法吗?

谢谢

2 个答案:

答案 0 :(得分:1)

因此,这段代码可能很难看,但是可以正常工作。我确信您可以清理它,但是它可以完成工作(只要您愿意,就可以创建一个新文件并复制并粘贴它,如果找不到更好的算法,请告诉我,然后我很乐意提供帮助):

public class contract {

  public contract(){

  }
  public static String replaceContractNo(String pMessage, String pInput, String pOutput) {

      return pMessage.replaceAll(pInput, pOutput);
    }

    public static void main(String args[]){

      contract myContract = new contract();

      String message = "hi John. You have two contracts listed: TV-70002548 and FV-50006578. The first contract ends on March 15th. I will pay you a final amount of 350 $.";

      int start1 = message.indexOf("TV");
      System.out.println(start1);
      int end1 = message.indexOf(' ', start1);
      System.out.println(end1);
      String str1 = message.substring(start1, end1);
      System.out.println(str1);

      String test1 = replaceContractNo(str1, "0", "null");
      System.out.println("test1 = "+test1);

      int start2 = message.indexOf("FV");
      int end2 = message.indexOf(' ', start2);
      String str2 = message.substring(start2, end2);

      String test2 = replaceContractNo(str2, "5", "five");
      System.out.println("test2 = " +test2);

      message = message.replaceAll(str1, test1);
      message = message.replaceAll(str2, test2);

      System.out.println(message);

        }

    }

答案 1 :(得分:0)

这是您要做什么吗?

str1.replaceAll(oldString, newString);