如果存在于 C# 中,则修剪美元符号的简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/154845/
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
Simple way to trim Dollar Sign if present in C#
提问by Brian G
I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present.
我有一个 DataRow,我得到了一个元素,它是一个带有美元符号的金额。我正在调用一个 toString 。是否有另一种方法可以调用它来删除美元符号(如果存在)。
So something like:
所以像:
dr.ToString.Substring(1, dr.ToString.Length);
dr.ToString.Substring(1, dr.ToString.Length);
But more conditionally in case the dollar sign ever made an appearance again.
但更有条件的是,万一美元符号再次出现。
I am trying to do this with explicitly defining another string.
我试图通过明确定义另一个字符串来做到这一点。
采纳答案by StingyHyman
Convert.ToString(dr(columnName)).Replace("$", String.Empty)
-- If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.
-- 如果您正在处理一个数据表,那么您必须将值(默认为它的对象)拆箱为一个字符串,因此您已经创建了一个字符串,然后是另一个替换的字符串。确实没有其他方法可以绕过它,但是在处理数以万计的操作时,您只会看到性能差异。
回答by itsmatt
Regex would work.
正则表达式会起作用。
Regex.Replace(theString, "$", "");
Regex.Replace(theString, "$", "");
But there are multiple ways to solve this problem.
但是有多种方法可以解决这个问题。
回答by devmode
dr[columeName].ToString().Replace("$", String.Empty)
dr[columeName].ToString().Replace("$", String.Empty)
回答by Kwirk
Why don't you update the database query so that it doesn't return the dollar sign? This way you don't have to futz with it in your C# code.
为什么不更新数据库查询,使其不返回美元符号?这样您就不必在 C# 代码中使用它。
回答by Shaun Bowe
If you are using C# 3.0 or greater you could use extension methods.
如果您使用的是 C# 3.0 或更高版本,则可以使用扩展方法。
public static string RemoveNonNumeric(this string s)
{
return s.Replace("$", "");
}
Then your code could be changed to:
那么您的代码可以更改为:
((String)dr[columnName]).RemoveNonNumeric();
This would allow you to change the implementation of RemoveNonNumeric later to remove things like commas or $ signs in foreign currency's, etc.
这将允许您稍后更改 RemoveNonNumeric 的实现,以删除外币中的逗号或 $ 符号等内容。
Also, if the object coming out of the database is indeed a string you should not call ToString() since the object is already a string. You can instead cast it.
此外,如果来自数据库的对象确实是一个字符串,则不应调用 ToString(),因为该对象已经是一个字符串。你可以改为投射它。
回答by hangy
You could also use
你也可以使用
string trimmed = (dr as string).Trim('$');
or
或者
string trimmed = (dr as string).TrimStart('$');