[英]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
: 您可以使用
string.Substring
:
s = "{" + s.Substring(1, s.Length - 2) + "}";
See it working online: ideone 看到它在线上工作: 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.. 如果您使用.Net 3和更高版本,并且不想使用扩展方法,则可以选择Lambda来获得比普通字符串操作更好的性能。
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.Concat(字符串的+运算符的内部实现调用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. 这比使用Substring和在边缘添加手镯快19倍 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.