从C#中的字符串中删除最后一个字符。优雅的方式? [英] Remove last characters from a string in C#. An elegant way?

查看:72
本文介绍了从C#中的字符串中删除最后一个字符。优雅的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数字字符串 2223,00 。我想将其转换为 2223 。这是:没有之后 之后的信息。假设在 之后只有两个小数。

I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".

我这样做了:

str = str.Remove(str.Length - 3, 3);

是否有更优雅的解决方案?也许使用其他功能? -我不喜欢放置显式数字-

Is there a more elegant solution? Maybe using another function? -I don´t like putting explicit numbers-

推荐答案

实际上,您可以使用带有一个参数的Remove重载:

You can actually just use the Remove overload that takes one parameter:

str = str.Remove(str.Length - 3);

但是,如果要避免对长度进行硬编码,可以使用:

However, if you're trying to avoid hard coding the length, you can use:

str = str.Remove(str.IndexOf(','));

这篇关于从C#中的字符串中删除最后一个字符。优雅的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆