简体   繁体   中英

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.

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.

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
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),"}");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM