开发者

How do i add a string after text if it's not already there?

开发者 https://www.devze.com 2023-02-04 20:14 出处:网络
How can i add a string after text if the string is not already there? I have a textbox w开发者_如何学编程ith the following lines:

How can i add a string after text if the string is not already there?

I have a textbox w开发者_如何学编程ith the following lines:

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

how can i add thumbnail:example.com after name:username to the second and third line but not the first line?


Edit: Didn't notice that you are reading from a textbox - you'll have to join the textbox lines to one string to use my example. You can do that with string.join() Try this... this assumes that there are no spaces allowed in the username. There are probably plenty of better/more efficient ways to do this, but this should work.

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


    }


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

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消