简体   繁体   English

如何在C#中删除字符串的第一个和最后一个字符?

[英]How to remove first and last character of a string in C#?

String: "hello to the very tall person I am about to meet"

What I want it to become is this:我想让它变成这样:

String: hello to the very tall person I am about to meet

I can only find code to trim the start?我只能找到代码来修剪开始?

Use the String.Substring method.使用 String.Substring 方法。

So, if your string is stored in a variable mystr , do as such:因此,如果您的字符串存储在变量mystr ,请执行以下操作:

mystr = mystr.Substring(1, mystr.Length - 2);

If you want to remove any first and last character from the string, then use Substring as suggested by Anish, but if you just want to remove quotes from beginning and the end, just use如果您想从字符串中删除任何第一个和最后一个字符,请按照 Anish 的建议使用 Substring,但如果您只想从开头和结尾删除引号,只需使用

myStr = myStr.Trim('"');

Note: This will remove all leading and trailing occurrences of quotes ( docs ).注意:这将删除所有前导和尾随引号 ( docs )。

If you are trying to remove specific characters from a string, like the quotes in your example, you can use Trim for both start and end trimming, or TrimStart and TrimEnd if you want to trim different characters from the start and end.如果您尝试从字符串中删除特定字符,例如示例中的引号,您可以使用Trim进行开始和结束修剪,或者如果您想从开始和结束修剪不同的字符,则可以使用TrimStartTrimEnd Pass these methods a character (or array of characters) that you want removed from the beginning and end of the string.将要从字符串开头和结尾删除的字符(或字符数组)传递给这些方法。

var quotedString = "\"hello\"";
var unQuotedString = quotedString.TrimStart('"').TrimEnd('"'); 

// If the characters are the same, then you only need one call to Trim('"'):
unQuotedString = quotedString.Trim('"');

Console.WriteLine(quotedString);
Console.WriteLine(unQuotedString);

Output:输出:

"hello" “你好”

hello你好

Alternatively, you can use Skip and Take along with Concat to remove characters from the beginning and end of the string.或者,您可以使用Skip and TakeConcat从字符串的开头和结尾删除字符。 This will work even for and empty string, saving you any worries about calculating string length:这甚至适用于空字符串,让您无需担心计算字符串长度:

var original = "\"hello\"";
var firstAndLastRemoved = string.Concat(original.Skip(1).Take(original.Length - 2));

C# 8: myString[1..^1] C# 8: myString[1..^1]
See Indices and ranges查看指数和范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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