在除空格之外的每个字符之间添加#

时间:2015-05-04 18:58:51

标签: c# winforms

我是初学者,在其他地方找不到任何东西。我在C#Windows窗体中编码。 这是我到目前为止所得到的:

private void button6_Click(object sender, EventArgs e)
    {
        string input = "The earth is flat or something";
        string hashtag = "#";            
        stringOutput.Text = input.Replace(" ", "?");           
    }

预期产量:     “T#ħ#E'E·一个#R·T#H + I#S'F#升#A#吨#”

2 个答案:

答案 0 :(得分:2)

循环遍历字符串并创建一个新字符串。

StringBuilder result = new StringBuilder();

foreach (char c in input)
{
    result.Append(c);
    if (c != ' ') {
         result.Remove(result.Length - 2, 1);
         result.Append('#');
    }
}

string resultAsString = result.ToString();

或使用正则表达式。

答案 1 :(得分:0)

You can easily do it with a simple loop or an Aggregate linq query method.

With foreach loop:

string toBeReplaced = "The earth is flat or something";
var sb = new StringBuilder();
foreach (var c in toBeReplaced)
{
    if (c != ' ')
    {
        sb.Append(c).Append('#');
    }
    else
    {
        sb.Append('?');
    }
}
string result = sb.ToString();

With Aggregate linq extension method:

string toBeReplaced = "The earth is flat or something";
string result = toBeReplaced.Aggregate(new StringBuilder(), (sb, c) => c != ' ' ? sb.Append(c).Append('#') : sb.Append('?')).ToString();