我正在尝试在字符串中的每个单词前后设置大括号'{}'。例如Hello everyone, is this my string.
,我想将其更改为{Hello} {everyone}, {is} {this} {my} {string}.
。为此,我使用以下代码拆分单词:
string a="Hello everyone is this my string.";
string[] words=a.Split(' ');
for(int i=0; i<words.Length; i++)
{
a=a.Replace(words[i],"{"+words[i]+"}");
}
代码运行良好,但这将is
替换为this
。我得到了这样的输出{Hello} {everyone}, {is} th{is} {my} {string}.
如何解决这个问题呢。预先感谢。
特定行为的原因是以下行。
a=a.Replace(words[i],"{"+words[i]+"}");
String.Replace将替换所有出现的特定字符串。因此,当您尝试替换is
时,最终也将替换is
中的this
子字符串。
您可以执行以下操作以获得正确的结果。
var originalString ="Hello everyone is this my string.";
var words= Regex.Replace(originalString,@"\b[^ ]+\b",@"{$0}");
这将确保按照OP中所需的答案来处理句点字符。
样品
Hello everyone is this my string.
{Hello} {everyone} {is} {this} {my} {string}.
Hello everyone, is this my string.
{Hello} {everyone}, {is} {this} {my} {string}.