C# 替换字符串中的第一次出现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10350699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:30:28  来源:igfitidea点击:

Replace the first occurrence in a string

c#.netreplace

提问by markzzz

I have this string :

我有这个字符串:

Hello my name is Marco

and I'd like to replace the first space (between Helloand my) with <br />. Only the first.

我想用.替换第一个空格(Hello和之间my<br />。只有第一个。

What's the best way to do it on C#/.NET 3.5?

在 C#/.NET 3.5 上执行此操作的最佳方法是什么?

采纳答案by Marshal

No need to add substrings, following will find the first space instance only. From MSDN:

不需要添加子串,后面只会找到第一个空格实例。从MSDN

Reports the zero-based index of the first occurrence of the specified string in this instance.

报告此实例中第一次出现指定字符串的从零开始的索引。

  string x = "Hello my name is Marco";
  int index = x.IndexOf(" ");
  x= index >=0 ? x.Insert(index, @"<br />") : x;

Edit:If you are not sure if space will occur, some validations must come into place. I have edit the answer accordingly.

编辑:如果您不确定是否会出现空间,则必须进行一些验证。我已经相应地编辑了答案。

回答by Steve Danner

string tmp = "Hello my name is Marco";
int index = tmp.IndexOf(" ");
tmp = tmp.Substring(0, index) + "<br />" + tmp.Substring(index + 1);

回答by Nikhil Agrawal

string[] str = "Hello my name is Marco".Split(' ');
string newstr = str[0] + "<br /> " + string.Join(" ", str.Skip(1).ToArray());

回答by Jamiec

Here you go, this would work:

给你,这行得通:

var s = "Hello my name is Marco";
var firstSpace = s.IndexOf(" ");
var replaced = s.Substring(0,firstSpace) + "<br/>" + s.Substring(firstSpace+1);

You could make this into an extension method:

你可以把它变成一个扩展方法:

public static string ReplaceFirst(this string input, string find, string replace){
  var first= s.IndexOf(find);
  return s.Substring(0,first) + replace + s.Substring(first+find.Length);
}

And then the usage would be

然后用法是

var s = "Hello my name is Marco";
var replaced = s.ReplaceFirst(" ","<br/>");

回答by Zaheer Ahmed

 public static class MyExtensions
 {

   public static string ReplaceFirstOccurrance(this string original, string oldValue, string newValue)
    {
     if (String.IsNullOrEmpty(original))
        return String.Empty;
     if (String.IsNullOrEmpty(oldValue))
        return original;
     if (String.IsNullOrEmpty(newValue))
        newValue = String.Empty;
     int loc = original.IndexOf(oldValue);
     return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
    }
}

and use it like:

并使用它:

string str="Hello my name is Marco";  
str.ReplaceFirstOccurrance("Hello", "<br/>");
str.ReplaceFirstOccurrance("my", "<br/>");