在c#中的每个单词之前和之后设置方括号

问题描述 投票:0回答:1

我正在尝试在字符串中的每个单词前后设置大括号'{}'。例如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}.如何解决这个问题呢。预先感谢。

c# asp.net
1个回答
3
投票

特定行为的原因是以下行。

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}.
© www.soinside.com 2019 - 2024. All rights reserved.