user1461166
user1461166

Reputation: 77

How can I replace the first and last char of a string in C#?

I have a simple question, and I did some research but couldn't find the right answer for it.

I have this string:

|She wants to eat breakfast|

I found the answer for replacing ALL the characters | with another character.

My idea is that I want to replace the first | with { and the last one with }.

I know this is easy, but I the answer for this question would really help me out.

Thanks in advance.

Upvotes: 1

Views: 9312

Answers (4)

YoryeNathan
YoryeNathan

Reputation: 14532

The fastest way to go would be this:

var str = "|She wants to eat breakfast|";

unsafe
{
    fixed (char* pt = str)
    {
        pt[0] = '{';
        pt[str.Length - 1] = '}';
    }
}

Console.WriteLine(str); // Prints: {She wants to eat breakfast}

You will need to enable unsafe code (Right-click project > properties > build > "Allow unsafe code".

This is about 19 times faster than using Substring and adding bracelets at the edges.

Upvotes: 0

sihirbazzz
sihirbazzz

Reputation: 718

If you use .Net 3 and higher and you don't want to use an extension method then you can prefer Lambda for a little bit better performance than normal string operations..

string s = "|she wants to eat breakfast|";
s.Replace(s.ToCharArray().First(ch => ch == '|'), '{'); //this replaces the first '|' char
s.Replace(s.ToCharArray().Last(ch => ch == '|'), '}'); // this replaces the last '|' char

Upvotes: 2

Steve
Steve

Reputation: 216363

string oldString = "|She wants to eat breakfast|";
string newString = "{" + oldString.SubString(1,oldString.Length-2) + "}";

or using string.Concat (the internal implementation of + operator for strings calls string.Concat)

string newString = string.Concat("{",oldString.SubString(1,oldString.Length-2),"}");

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 839184

You can use string.Substring:

s = "{" + s.Substring(1, s.Length - 2) + "}";

See it working online: ideone

This assumes that the characters you want to replace are the very first and last characters in the string.

Upvotes: 5

Related Questions