如果字符串不存在,如何在文本后添加字符串?
我有一个包含以下几行的文本框:
name:username thumbnail:example.com message:hello
name:username message:hi
name:username message:hey
Run Code Online (Sandbox Code Playgroud)
我怎样才能添加thumbnail:example.com到name:username第二行和第三行而不是第一行?
编辑:没有注意到您正在从文本框读取 - 您必须将文本框行连接到一个字符串才能使用我的示例。您可以使用 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));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2982 次 |
| 最近记录: |