从字符串 C# 中删除点字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10298940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:15:12  来源:igfitidea点击:

Remove dot character from a String C#

c#

提问by Pinchy

Assume I have a string "2.36" and I want it trimmed to "236"

假设我有一个字符串“2.36”,我想把它修剪为“236”

I used Trim function in example

我在示例中使用了 Trim 功能

String amount = "2.36";
String trimmedAmount = amount.Trim('.'); 

The value of trimmedAmount is still 2.36

trimmedAmount 的值仍然是 2.36

When amount.Trim('6');it works perfectly but with '.'

amount.Trim('6');它完美运行但带有 '.' 时

What I am doing wrong?

我做错了什么?

Thanks a lot Cheers

非常感谢干杯

采纳答案by Oded

Trimming is removing characters from the start or end of a string.

修剪是从字符串的开头或结尾删除字符。

You are simply trying to remove the ., which can be done by replacingthat character with nothing:

您只是想删除.,这可以通过用空替换该字符来完成:

string cleanAmount = amount.Replace(".", string.Empty);

回答by Ste

String.Trimremoves leading and trailing whitespace. You need to use String.Replace()

String.Trim删除前导和尾随空格。你需要使用String.Replace()

Like:

喜欢:

string amount = "2.36"; 
string newAmount = amount.Replace(".", ""); 

回答by ykatchou

Two ways :

两种方式:

string sRaw = "5.32";
string sClean = sRaw.Replace(".", "");

Trim is make for removing leading and trailings characters (such as space by default).

Trim 用于删除前导和尾随字符(例如默认情况下的空格)。

回答by Guffa

If you want to remove everything but the digits:

如果要删除除数字以外的所有内容:

String trimmedAmount = new String(amount.Where(Char.IsDigit).ToArray());

or:

或者:

String trimmedAmount = Regex.Replace(amount, @"\D+", String.Empty);