【问题标题】:How do i add a string after text if it's not already there?如果它不存在,我如何在文本之后添加一个字符串?
【发布时间】:2011-01-17 03:00:35
【问题描述】:

如果字符串不存在,如何在文本后添加字符串?

我有一个包含以下行的文本框:

name:username thumbnail:example.com message:hello
name:username message:hi
name:username message:hey

如何在name:username 之后将thumbnail:example.com 添加到第二行和第三行而不是第一行?

【问题讨论】:

  • 他们都有不同的缩略图,用户名和消息是完全动态的,我应该提到这一点。
  • 我们可以说所有行的格式都是 a)name:XXX thumbnail:YYY message:ZZZ 或 b)name:XXX message:ZZZ
  • 如果用户名中有空格,即name:XXX YYY

标签: c# winforms text


【解决方案1】:

编辑:没有注意到您正在从文本框阅读 - 您必须将文本框的行连接到一个字符串才能使用我的示例。你可以用 string.join() 做到这一点 试试这个......这假设用户名中不允许有空格。可能有很多更好/更有效的方法可以做到这一点,但这应该可行。

    var sbOut = new StringBuilder();
    var combined = String.Join(Environment.NewLine, textbox1.Lines);
    //split string on "name:" rather than on lines
    string[] lines = combined.Split(new string[] { "name:" }, StringSplitOptions.RemoveEmptyEntries);
    foreach (var item in lines)
    {
        //add name back in as split strips it out
        sbOut.Append("name:");
        //find first space
        var found = item.IndexOf(" ");
        //add username IMPORTANT assumes no spaces in username
        sbOut.Append(item.Substring(0, found + 1));
        //Add thumbnail:example.com if it doesn't exist
        if (!item.Substring(found + 1).StartsWith("thumbnail:example.com"))                
            sbOut.Append("thumbnail:example.com ");
        //Add the rest of the string
        sbOut.Append(item.Substring(found + 1));


    }

【讨论】:

  • 谢谢,经过一些修改,我使用了这种方法,现在效果很好!
【解决方案2】:

var lines = textbox.Text.Split(new string[] { Environment.NewLine.ToString() }, StringSplitOptions.RemoveEmptyEntries);

        textbox.Text = string.Empty;

        for (int i = 0; i < lines.Length; i++)
        {
            if (!lines[i].Contains("thumbnail:example.com") && lines[i].Contains("name:"))
            {
                lines[i] = lines[i].Insert(lines[i].IndexOf(' '), " thumbnail:example.com");
            }
        }

        textbox.Text = string.Join(Environment.NewLine, lines);

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2022-01-08
    • 2011-02-21
    • 1970-01-01
    • 2015-07-10
    • 2015-07-05
    相关资源
    最近更新 更多