[英]Remove last specific character in a string c#
I use WinForms c#.I have string value like below,我使用 WinForms c#。我有如下的字符串值,
string Something = "1,5,12,34,";
I need to remove last comma in a string.我需要删除字符串中的最后一个逗号。 So How can i delete it ?
那么我该如何删除它呢?
尝试string.TrimEnd()
:
Something = Something.TrimEnd(',');
King King's answer is of course correct, and Tim Schmelter's comment is also good suggestion in your case. King King 的回答当然是正确的, Tim Schmelter 的评论对您的情况也是很好的建议。
But if you really want to remove the last comma in a string , you should find the index of the last comma and remove it like this:但是如果你真的想删除 string 中的最后一个逗号,你应该找到最后一个逗号的索引并像这样删除它:
string s = "1,5,12,34,12345";
int index = s.LastIndexOf(',');
Console.WriteLine(s.Remove(index, 1));
Output will be:输出将是:
1,5,12,3412345
Here is a demonstration
.这是一个
demonstration
。
It is unlikely that you want this way but I want to point it out.您不太可能想要这种方式,但我想指出这一点。 And remember, the
String.Remove
method doesn't remove any characters in the original string, it returns new string.请记住,
String.Remove
方法不会删除原始字符串中的任何字符,它返回新字符串。
Try string.Remove();
试试
string.Remove();
string str = "1,5,12,34,";
string removecomma = str.Remove(str.Length-1);
MessageBox.Show(removecomma);
The TrimEnd method takes an input character array and not a string. TrimEnd 方法采用输入字符数组而不是字符串。 The code below from Dot Net Perls , shows a more efficient example of how to perform the same functionality as TrimEnd.
下面来自Dot Net Perls的代码显示了一个更有效的示例,说明如何执行与 TrimEnd 相同的功能。
static string TrimTrailingChars(string value)
{
int removeLength = 0;
for (int i = value.Length - 1; i >= 0; i--)
{
char let = value[i];
if (let == '?' || let == '!' || let == '.')
{
removeLength++;
}
else
{
break;
}
}
if (removeLength > 0)
{
return value.Substring(0, value.Length - removeLength);
}
return value;
}
Try below试试下面
Something..TrimEnd(",".ToCharArray());东西..TrimEnd(",".ToCharArray());
Or you can convert it into Char Array first by:或者您可以先通过以下方式将其转换为 Char Array:
string Something = "1,5,12,34,";
char[] SomeGoodThing=Something.ToCharArray[];
Now you have each character indexed
:现在你有每个字符
indexed
:
SomeGoodThing[0] -> '1'
SomeGoodThing[1] -> ','
Play around it玩转它
Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))
output:输出:
1,5,12,34,123
When you have spaces at the end.当你最后有空格时。 you can use beliow.
你可以使用下面。
ProcessStr = ProcessStr.Replace(" ", "");
Emails = ProcessStr.TrimEnd(';');
试试这个,stringSomething1=Something.Substring(0,Something.Length - 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.