【问题标题】:Replace strings in a long String:替换长字符串中的字符串:
【发布时间】:2013-05-05 13:01:25
【问题描述】:

我有以下字符串:

您在哪里 [员工姓名]? 你有 [Shift] 班次...

以及包含以下内容的字符串列表:

1.员工姓名

2. 换档

我需要在长字符串的列表中找到给定的字符串,并将它们替换为另一个内容(包括[] 字符)。 因此,例如第一个字符串需要更改为:

Jhon Green 你在哪里? 你有早班...

有什么简单的方法吗?使用 IndexOf 会给我这个字符串的位置,但是我如何包含 [] 字符呢?

更新: 这是我目前测试的代码:

    Scanner sc = new Scanner(smsText);

    for (String s; (s = sc.findWithinHorizon("(?<=\\[).*?(?=\\])", 0)) != null;) 
    {
         words.add(s);
    }

    for (int j = 0; j < words.size(); j++)  
    {  
        Log.d(TAG, "The value for column: "+words.get(j) +" is: "+ rowData.getValue(words.get(j)));
        smsText.replaceFirst("\\[" + words.get(j) + "\\]", rowData.getValue(words.get(j)));
    }

    Log.d(TAG, "Final String is: "+ smsText);

这没有给我正确的结果,字符串没有被替换。

更新 2: 对我有用的解决方案是:

    Scanner sc = new Scanner(smsText);

    for (String s; (s = sc.findWithinHorizon("(?<=\\[).*?(?=\\])", 0)) != null;) 
    {
         columnNames.add(s);
    }

    for (int j = 0; j < columnNames.size(); j++)  
    {  
        Log.d(TAG, "The value for column: "+columnNames.get(j) +" is: "+ rowData.getValue(columnNames.get(j)));
        smsText = smsText.replaceFirst("\\[" + columnNames.get(j) + "\\]", rowData.getValue(columnNames.get(j)));
    }
    Log.d(TAG, "Final String is: "+ smsText);

感谢大家的帮助。

【问题讨论】:

  • 如果您可以控制模板,请将其切换为%s 并使用String.format()
  • @CommonsWare,不幸的是我没有,“[”和“]”里面的短语是一个列名,我需要从中提取替换的内容,所以它不能被改变要么。
  • @EmilAdz 这个字符串Where Are You [Employee Name]? your have a [Shift] shift 常见吗?你想用员工的名字替换[Employee Name]吗?告诉我
  • 整个字符串以及员工姓名字符串都是动态的,可以从服务器端更改。
  • 你需要从 replaceFirst 中保存你的结果:smsText = smsText.replaceFirst(...

标签: java android string indexof


【解决方案1】:
String key = myColumns.getName();
s.replaceFirst("\\[" + key + "\\]", myReplacements.getReplacement(key));

您也可以使用indexOf,但使用替换功能可以立即清楚您要做什么。

【讨论】:

  • Employee Name 和 Shift 是代表列名的参数,将被更改(这只是一个案例示例)。所以我需要一个更通用的解决方案。
  • 谢谢@nullptr,给我几分钟来测试一下。
  • 查看更新的问题,由于某种原因,这对我不起作用。
【解决方案2】:

试试这个

    String s = "Where Are You [Employee Name]? your have a [Shift] shift..";
    Map<String, String> replacementMap = new HashMap<>();
    replacementMap.put("[Employee Name]", "John Green");
    replacementMap.put("[Shift]", "morning");
    for(Entry<String, String> e : replacementMap.entrySet()) {
        s = s.replace(e.getKey(), e.getValue());
    }
    System.out.println(s);

输出

Where Are You John Green? your have a morning shift..

【讨论】:

  • 我需要替换那些字符串,而不是像上一个问题那样找到它们。
  • @EmilAdz 当你找到它们时很容易替换检查这个browxy.com/SubmittedCode/18488
【解决方案3】:

一般的解决方案可能如下所示:

String message = "Where are you [Employee Name]? You have a [Shift] shift!";
Map<String, String> variables = new HashMap<>();
variables.put("Employee Name", "John Green");
variables.put("Shift", "morning");
StringBuffer endResult = new StringBuffer();
Matcher m = Pattern.compile("\\[(.*?)\\]").matcher(message);
while (m.find()) {
    m.appendReplacement(endResult, variables.get(m.group(1)));
}
m.appendTail(endResult);
System.out.println(endResult.toString());

【讨论】:

    【解决方案4】:

    我知道有正则表达式,但如果你想在这里使用递归函数,那就是

       public string replaceString(string str, string[] values, int index)
        {
            if (str.IndexOf('[') == -1 || str.IndexOf(']') == -1 || index > values.Length-1)
                return str;
            else
    
                return replaceString(str.Replace(str.Substring(str.IndexOf('['), (str.IndexOf(']') - str.IndexOf('['))+1), values[index]), values, ++index);
        }
    

    调用这个方法

         string strforreplac = "Where Are You [Employee Name]? your have a [Shift] shift...]";
               string[] strvalues = {"Emil","morning"};
          string newstring = replaceString(strforreplac,strvalues,0);
    

    【讨论】:

      猜你喜欢
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 2013-01-04
      • 2012-04-03
      • 1970-01-01
      • 2013-07-23
      • 2013-11-05
      相关资源
      最近更新 更多