markzzz
markzzz

Reputation: 47945

Replace the first occurrence in a string

I have this string :

Hello my name is Marco

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

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

Upvotes: 4

Views: 29433

Answers (6)

Marshal
Marshal

Reputation: 6661

No need to add substrings, following will find the first space instance only. From 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(" ");
  if (index >= 0)
  {
      x=x.Remove(index,1);
      x = x.Insert(index, @"<br />");
  }

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

Upvotes: 5

knoami
knoami

Reputation: 605

Simply use

Replace("Hello my name is Marco", " ", "<br />", 1, 1)

Upvotes: 0

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28548

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

Upvotes: 12

Jamiec
Jamiec

Reputation: 136114

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

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

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

Upvotes: 0

Steve Danner
Steve Danner

Reputation: 22158

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

Upvotes: 3

Related Questions