我有一个简单的问题,我做了一些研究,但没有找到正确的答案。
我有一根绳子:
她想吃早餐
我找到了用另一个字符替换所有字符|的答案。
我的想法是,我想用{代替第一个{,用}代替最后一个。
我知道这很容易,但我对这个问题的答案会对我有帮助。
提前谢谢。
发布于 2012-06-16 22:28:30
您可以使用string.Substring
s = "{" + s.Substring(1, s.Length - 2) + "}";看到它在网上工作:意为
这假设要替换的字符是字符串中的第一个和最后一个字符。
发布于 2012-06-16 23:12:06
如果您使用.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发布于 2012-06-16 22:29:05
string oldString = "|She wants to eat breakfast|";
string newString = "{" + oldString.SubString(1,oldString.Length-2) + "}";或者使用string.Concat (字符串调用string.Concat的+操作符的内部实现)
string newString = string.Concat("{",oldString.SubString(1,oldString.Length-2),"}");https://stackoverflow.com/questions/11067527
复制相似问题