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.
So something like:
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.
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.
You could also use
string trimmed = (dr as string).Trim('$');
or
string trimmed = (dr as string).TrimStart('$');
If you are using C# 3.0 or greater you could use extension methods.
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.
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.
Regex would work.
Regex.Replace(theString, "$", "");
But there are multiple ways to solve this problem.
dr[columeName].ToString().Replace("$", String.Empty)
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.
Related
I have the following field that is calling the database Phone_Number. I would like to remove the 1- when the number is displayed.
So instead of displaying 1-###-###-####, I would like to display ###-###-####.
I tried the following:
string x= Phone_Number;
x.Remove(0,1);
Response.Write(x);
However, it keeps displaying 1-###-###-####.
What am I doing wrong?
Strings are immutable in C# - String.Remove call does not modify original string. It creates the new string in which specified characters are deleted and returns it. You should display result of this method call instead:
Response.Write(x.Remove(0,2)); // you should remove 2 characters
Or
Response.Write(x.Substring(2));
You need to set the result to x. strings are immutable in C#:
x = x.Remove(0,1)
Another method would be:
if (x.StartsWith("1-")
x = x.Remove(0,2);
This has the benefit of doing nothing if you get a phone number without the leading 1-.
Thanks to commenter for pointing out my error.
As you see there are too many ways to remove substrings from strings. A new way that you can also use is a Regular Expression just in case the value you want to remove have a complex pattern in the future.
var x = phoneNumber;
var result = Regex.Match(x, #"^(1-)?(.*)$").Groups[2].Value;
assume that there is a string named "message", and assume an user type in the console,
"!My FB List", but words "FB" and "List" could be change. But "!My" won't change. So, I want to save the text the user type. Only if user used "!My" before the other words.
So, I don't know how to get this to 'if' command. Plz help me.
if (message == "!My "
Do you mean something like this?
if (message.StartsWith("!My "))
{
// do something
}
This code works in most situations. However, if you need to resolve situations like Kshitij Mehta mentioned in the comments, you'd be probably better off with a Split method parsing the string and comparing the first object of the array to the required string.
When you've split the input string into an array, you will just compare strings in a typical fashion (==), probably no need for fancy methods in that scenario.
One more "however" to consider - if your input string is long, splitting might not be the best idea to do. In that case I'd probably use regular expressions to compare the beginning of the inputted string.
The implementation depends on your needs. Just pick what suits you the best :)
It sounds like you want to accept commands and then do specific things based on those commands. Apparently, the "command" is the first word in the text typed by the user.
Thus, I'd split the message at whitespace and then switch for the first word:
var words = message.Split();
var command = words[0];
switch (command) {
case "!My":
// Do something
...
break;
case "!SomethingElse":
// Do something else
...
break;
...
}
Afterwards, you can use words[1] to get "FB" and words[2] to get "list". Be sure to use words.Length to verify if the required number of parameters has been specified before trying to access them.
String class includes many static methods, among which is StartsWith().
so your if statement can simply be
if(UserString.StartsWith("!My"))
{
// other conditional code here
}
It is not clear from your question whether you want to include cases where the user types "!My" before typing anything else, but he/she does NOT type a space immediately after typing !My.
If you only want to process the code if the three characters "!My" were followed by a space, then, (as suggested by #Walther), add a space to the test string in the StartsWith() method
if(UserString.StartsWith("!My "))
{
// other conditional code here
}
really simple question... just want to represent double quote " without needing to do "" or \"
cases that I'm aware of:
var s=#"123 "" 456 """;
var s="123 \" 456 \"";
It'd make a reasonalbe difference if I could remove this noise somehow. The reason is that the escape sequence \ and the double quote have meaning in a domain specific language (DSL) that we're using. Sometimes it's convenient to throw some syntax inline into a C# string.
What I'd like is a way to tell .net not to touch it. Perhaps some kind of catch all via the DLR?
Within a C# literal, there's nothing you can to - don't forget this is all done at compile-time.
If you don't use single quotes, you could always do:
var s = "123 ' 456 '".Replace("'", "\"");
(Or choose some other character you don't use much, and replace that afterwards instead.)
Other than that, avoiding storing lots of data in your source code helps a lot with this sort of thing - for test data, I often use an embedded resource and load that in at execution time.
I don't suppose you could just read them in from a file or database?
Yeah, there's definitely a way to do that, and I use it all the time for exactly that reason.
You create a string resource collection (open Project Properties, Resources, make sure it's on Strings) and put your literal strings in there. Then, when you need one of those strings, use the Properties.Resources.{insert string resource name} reference to collect it in a pure and unadulterated form!
For completeness, I'll mention that you can use hex in a C# string, so in this case, \x0022. Note that you can omit the leading 0's if the character immediately following isn't hex.
Let's say I have this string:
"param1,r:1234,p:myparameters=1,2,3"
...and I would like to split it into:
param1
r:1234
p:myparameters=1,2,3
I've used the split function and of course it splits it at every comma. Is there a way to do this using regex or will I have to write my own split function?
Personally, I would try something like this:
,(?=[^,]+:.*?)
Basically, use a positive look-ahead to find a comma, followed by a "key-value" pair (this defined by a key, a colon, and more information [data] (including other commas). This should disqualify the commas between the numbers, too.
You can use ; for separating values which makes easy to work with it.
Since you have , for separation and also for values it is difficult to split it.
You have
string str = "param1,r:1234,p:myparameters=1,2,3"
Recommended to use
string str = "param1;r:1234;p:myparameters=1,2,3"
which can be splited as
var strArray = str.Split(';');
strArray[0]; // contains param1
strArray[1]; // r:1234
strArray[2]; // p:myparameters=1,2,3
I'm not sure how you would write a split that knew which commas to split on there, honestly.
Unless it's a fixed number each time in which case, just use the String.Split overload that takes an int specifying how many substrings to return at max
If you're going to have comma-delimited data that's not always a fixed number of items and it could have literal commas in the data itself, they really should be quoted. If you can control the input in any way, you should encourage that, and use an actual CSV parser instead of String.Split
That depends. You can't parse it with regex (or anything else) unless you can identify a consistent rule separating one group from another. Based on your sample, I can't clearly identify such a rule (though I have some guesses). How does the system know that p:myparameters=1,2,3 is a single item? For example, if there were another item after it, what would be the difference between that and the 1,2,3? Figure that out and you'll be pretty close to a solution.
If you're able to change the format of the input string, why not decide on a consistent delimiter between your groups? ; would be a good choice. Use an input like param1;r:1234;p:myparameters=1,2,3 and there will be no ambiguity where the groups are, plus you can just split on ; and you won't need regex.
The simplest approach would be changing your delimiter from "," to something like "|". Then you can split on "|" no problem. However if you can't change the delimiting character then maybe you could encode the sections in a fashion similar to CSV.
CSV files have the same issue... the standard there is to put double quotes "" around columns.
For example, your string would be "param1","r:1234","p:myparameters=1,2,3".
Then you could use the Microsoft.VisualBasic.FileIO.TextFieldParser to split/parse. You can include this in c# even though its in the VisualBasic namespace.
TextFieldParser
Do you mean that:string[] str = System.Text.RegularExpression.Regex.Spilt("param1,r:1234,p:myparameters=1,2,3",#"\,");
I get from another class string that must be converted to char. It usually contains only one char and that's not a problem. But control chars i receive like '\\n' or '\\t'.
Is there standard methods to convert this to endline or tab char or i need to parse it myself?
edit:
Sorry, parser eat one slash. I receive '\\t'
I assume that you mean that the class that sends you the data is sending you a string like "\n". In that case you have to parse this yourself using:
Char.Parse(returnedChar)
Otherwise you can just cast it to a string like this
(string)returnedChar
New line:
string escapedNewline = #"\\n";
string cleanupNewLine = escapedNewline.Replace(#"\\n", Environment.NewLine);
OR
string cleanupNewLine = escapedNewline.Replace(#"\\n", "\n");
Tab:
string escapedTab = #"\\t";
string cleanupTab= escapedTab.Replace(#"\\t", "\t");
Note the lack of the literal string (i.e. i did not use #"\t" because that will not represent a Tab)
Alternatively you could consider Regular Expressions if you need to replace a range of different string patterns.
You should probably write a utility function to encapsulate the common behaviour above for all the possible Escape Sequences
Then you'd write some Unit Tests to cover each of the cases you can think of.
As you encounter any bugs you add more unit tests to cover those cases.
UPDATE
You could represent a tab in the XML with a special character sequence:
see this article
This article applies to SQL Server but may well be relevant to C# also?
To be absolutely sure, you could try generating a string with a tab in it and putting it into some XML (programmatically) and using XmlSerializer to serialize that to a file to see what the output is, then you can be sure that this will faithfully 'round-trip' the string with the tab still in it.
how about using string.ToCharArray()
You can then add the appropriate logic to process whatever was in the string.
char.parse(string); is used to convert string to char and you can do vice versa
char.tostring();
100% solved