我有一个字符串,它是一个或两个长的句子(超过一个词)。在那个句子中会有一个带有哈希标签的单词,例如#word
。这需要替换为*word*
.
如果句子是:
Today the weather is very nice #sun
它应该变成:
Today the weather is very nice *sun*
我该怎么做呢?
你可以做一个正则表达式,像这样:
var output = Regex.Replace(input, @"#(\w+)", "*$1*");
你可以试试这个
string text = "Today the weather is very nice #sun";
int startindex = text.Indexof('#');
int endindex = text.IndexOf(" ", startIndex);
text = text.Replace(text.substring(startIndex, 1), "*")
text = text.Replace(text.substring(endindex, 1), "*")
试试这个:
string theTag = "sun";
string theWord = "sun";
string tag = String.Format("#{0}", theTag);
string word = String.Format("*{0}*", theWord);
string myString = "Today the weather is very nice #sun";
myString = myString.Replace(tag, word);
没有花哨的函数或库,只是常识并解决了您的问题。它支持任意数量的散列词。
为了演示它是如何工作的,我以 ac# 形式创建了 1 个文本框和 1 个按钮,但您可以在控制台或几乎任何东西中使用此代码。
string output = ""; bool hash = false;
foreach (char y in textBox1.Text)
{
if(!hash) //checks if 'hash' mode activated
if (y != '#') output += y; //if not # proceed as normal
else { output += '*'; hash = true; } //replaces # with *
else if (y != ' ') output += y; // when hash mode activated check for space
else { output += "* "; hash = false; } // add a * before the space
} if (hash) output += '*'; // this is needed in case the hashed word ends the sentence
MessageBox.Show(output);
看哪
Today the weather is very nice #sun
变成
Today the weather is very nice *sun*
这是相同的代码,但采用方法形式,您可以直接在代码中弹出
public string HashToAst(string sentence)
{
string output = ""; bool hash = false;
foreach (char y in sentence)
{
if (!hash)
if (y != '#') output += y;
else { output += '*'; hash = true; } // you can change the # to anything you like here
else if (y != ' ') output += y;
else { output += "* "; hash = false; } // you can change the * to something else if you want
} if (hash) output += '*'; // and here also
return output;
}
演示如何修改下面是一个可定制的版本
public string BlankToBlank(string sentence,char search,char highlight)
{
string output = ""; bool hash = false;
foreach (char y in sentence)
{
if (!hash)
if (y != search) output += y;
else { output += highlight; hash = true; }
else if (y != ' ') output += y;
else { output += highlight+" "; hash = false; }
} if (hash) output += highlight;
return output;
}
因此,搜索将在单词之前搜索字符,并且突出显示字符将围绕该单词。单词被定义为字符,直到它到达空格或字符串的末尾。