替换c#中的字符串字符

时间:2013-06-04 00:57:42

标签: c# asp.net string

我有一个或两个长句(多个单词)的字符串。在该句子中将有一个散列标记的单词,例如#word。这需要替换为*word*

如果句子是:

Today the weather is very nice #sun

应该成为:

Today the weather is very nice *sun*

我将如何做到这一点?

4 个答案:

答案 0 :(得分:8)

你可以做一个正则表达式,如下所示:

var output = Regex.Replace(input, @"#(\w+)", "*$1*");

答案 1 :(得分: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), "*")

答案 2 :(得分:0)

试试这个:

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);

答案 3 :(得分:0)

没有奇特的功能或库只是常识并解决您的问题。它支持任意数量的哈希单词。

为了演示它是如何工作的,我在c#表单中创建了1个TextBox和1个Button,但你可以在控制台中使用这个代码或几乎任何东西。

      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;
    }

因此搜索将在单词之前搜索字符,并且高亮显示字符将围绕单词。 Word被定义为字符,直到它到达空格或字符串的末尾。