2012-11-29 46 views
0

我有一个字符串,它具有某些“标记”。
实施例:在字符串中分析并替换值可互换

"Someone e.g. X here is a # and the other i.e. X is not but over is something else like #" 

我也有字符串例如列表{"John", "doctor", "Jim","engineer"}

什么是做到以下几点最好的办法:我想在列表中的相应的元素来取代所有#字符

I.e.我想跳过XJohn,并从#engineer替换Jim替换其他#
我以为只是循环了string#toCharArray(),但我有兴趣是否有更好的方法来做到这一点。

注意:第二个列表中的值匹配对应的标记。因此,列表中的第一个值即John映射到第一次出现X#,这是以前的情况。

例子:

输入:"Someone e.g. X here is a # and the other i.e. X is not but the other is something else like # but X is at least X but not #"
{"John", "doctor", "Jim","John", "engineer", "doctor"}
输出:
"Someone e.g. X here is a doctor and the other i.e. X is not but the other is something else like Jim but X is at least X but not doctor"

+2

你的问题是不可能的。如何向我们展示输入和期望的输出。 – Bohemian

+0

@波希米亚:查看更新 – Jim

回答

2

你可能有兴趣看看MessageFormat,允许类似这种替换的东西。

E.g.

MessageFormat.format("" 
    + "Someone e.g. {0} here is a {1} and the other i.e. {2} " 
    + "is not but over is something else like {3}", 
    new String [] {"John", "doctor", "Jim","engineer"}); 

编辑

如果输入字符串不能被修改,以包括占位符,并占位符必须为你在更新中提到的特殊含义(即X应该被忽略,#应及时更换),那么你只需要

  • 初始化计数器为0
  • 创建的StringBuilder的对象。
  • 记号化空间
  • 迭代输入串通过每个令牌
    • 如果是X,递增计数器,追加令牌作为是对StringBuilder对象。
    • 如果它是#,则从输入数组中读取索引counter上的值并将其附加到StringBuilder对象。
    • 追加一个空格。
  • StringBuilder.toString()并修剪以去除尾部空间。
+0

该字符串已经采用我描述的格式。我无法将其修改为您所说的 – Jim

+0

经过您的编辑,我更新了我的回复。请参阅编辑。 – Vikdor

+0

嗯,我不太确定使用空格分隔。字符串要复杂得多,但我明白了。 这与我以为使用'toCharArray'类似。如果没有更好的答案,我会接受这个 – Jim