C# PadLeft not working - c#

I have an issue with taking a number string from SQL and putting it into excel, but excel formats the number without it's leading zeros.
Another program I wrote reads the excel and put it into a pdf. It is in this second program I decided to reappend the missing leading zeros.
I am using .PadLeft to do this and ran into some errors. For documentation sake, I am going to add this issue I found to SO and also answer it.
Here was my problem:
I need the number string to be 10 digits, with zeros on the front up to 10 digits.
I have numbers like 77776666 coming from excel, they should be 0077776666 (10 digits)
Here is what DIDN'T work. It did not append any zeros:
string insuranceID = Convert.ToString(xlRange.Cells[i, 21].Value2 ?? "");
insuranceID.PadLeft(10, '0');

To make this code work, I actually had to write the code like so:
string insuranceID = Convert.ToString(xlRange.Cells[i, 21].Value2 ?? "");
insuranceID = insuranceID.PadLeft(10, '0');
It had to have the assignment part of the code on the front of the .PadLeft bit.
I didn't find an answer to this on SO and just discovered my answer. I hope this helps someone.

In C# Strings/strings are immutable, so simply declaring string.PadLeft(x, '0') will not work.
Try this instead:
string insuranceID = Convert.ToString(xlRange.Cells[i, 21].Value2 ?? "");
insuranceID = insuranceID.PadLeft(10, '0');
To save you time in the future, the immutability of strings also comes into play for many of the string methods such as string.Replace(), string.ToUpper(), string.ToLower(), etc.

You could have also just used your original code but append the .PadLeft(10, '0') to the end of your statement and remove your second line, like this:
string insuranceID = Convert.ToString(xlRange.Cells[i, 21].Value2 ?? "").PadLeft(10, '0');
Thus eliminating the need to create a separate statement other than possibly for debugging purposes.

Related

Can't replace single whitespace with string.Replace()

I have run into a problem I do not understand. I am reading data from a file and have run into a situation where string.Replace(" ", "<whatever>") on an entry from the file will not replace the occurence of a single whitespace. I cannot help but to feel there is something very basic that I have missed, since the same kind of string declared as a literal works fine.
A typical line from the file (each entry is separated by a tab):
"2016-feb-08 09:54:00" "2016-feb-08 17:28:00" "Short" "227" "5 170,00" "+3,90%" "0,00"
The data from the file is read into an array using File.ReadAllLines().Split(new[] {"\t" }, StringSplitOptions.None);.
I then want to clean up the fifth entry for further processing, and this is when I run into the problem:
entries[4].Replace(" ", string.Empty).Replace("\"", string.Empty); gives "5 170,00"
Regex.Replace(entries[4], #"\s+", string.Empty).Replace("\"", string.Empty); gives "5170,00", which is the result I am looking for.
Running the first Replace() on a literal with a single space works fine, so I am curious if the whitespace inside the strings from the file are different somehow? And while the Regex solution works, I really want to know what my "issue" is.
You can use code like below to check hex values of the character. A normal space is 0x20 which the value showing between the five and the one in the code you posted.
string input = "2016-feb-08 09:54:00 2016-feb-08 17:28:00 Short 227 5 170,00 +3,90% 0,00";
byte[] output = Encoding.UTF8.GetBytes(input);

what is the best way to parse out string from longer string?

i have a string that looks like this:
"/dir/location/test-load-ABCD.p"
and i need to parse out "ABCD" (where ABCD will be a different value every day)
The only things that i know that will always be consistent (to use for the logic for parsing) are:
There will always be be a ".p" after the value
There will always be a "test-load-" before the value.
The things i thought of was somehow grab everything past the last "/" and then remove the last 2 characters (to take case of the ".p" and then to do a
.Replace("test-load-", "")
but it felt kind of hacky so i wanted to see if people had any suggestions on a more elegant solution.
You can use a regex:
static readonly Regex parser = new Regex(#"/test-load-(.+)\.p");
string part = parser.Match(str).Groups[1].Value;
For added resilience, replace .+ with a character class containing only the characters that can appear in that part.
Bonus:
You probably next want
DateTime date = DateTime.ParseExact(part, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Since this is a file name, use the file name parsing facility offered by the framework:
var fileName = System.IO.Path.GetFileNameWithoutExtension("/dir/location/test-load-ABCD.p");
string result = fileName.Replace("test-load-", "");
A “less hacky” solution than using Replace would be the use of regular expressions to capture the solution but I think this would be overkill in this case.
string input = "/dir/location/test-load-ABCD.p";
Regex.Match(input, #"test-load-([a-zA-Z]+)\.p$").Groups[1].Value

Parsing a String for Special characters in C#

I am getting a string in the following format in the query string:
Arnstung%20Chew(20)
I want to convert it to just Arnstung Chew.
How do I do it?
Also how do I make sure that the user is not passing a script or anything harmful in the query string?
string str = "Arnstung Chew (20)";
string replacedString = str.Substring(0, str.IndexOf("(") -1 ).Trim();
string safeString = System.Web.HttpUtility.HtmlEncode(replacedString);
It's impossible to provide a comprehensive answer without knowing what variations might appear on your input text. For example, will there always be two words separated by a space followed by a number in parentheses? Or might there be other variations as well?
I have a lot of parsing code on my Black Belt Coder site, including a sscanf() replacement for .NET that may potentially be useful in your case.

c# convert string that has ctrl+z to regular string

i have a string like this:
some_string="A simple demo of SMS text messaging." + Convert.ToChar(26));
what is the SIMPLEST way of me getting rid of the char 26?
please keep in mind that sometimes some_string has char 26 and sometimes it does not, and it can be in different positions too, so i need to know what is the most versatile and easiest way to get rid of char 26?
If it can be in different positions (not just the end):
someString = someString.Replace("\u001A", "");
Note that you have to use the return value of Replace - strings are immutable, so any methods which look like they're changing the contents actually return a new string with the appropriate changes.
If it's only at the end:
some_string.TrimEnd((char)26)
If it can be anywhere then forget this and use Jon Skeet's answer.

String Format Does Not Works For string

I have a serial number which is String type.
Like This;
String.Format("{0:####-####-####-####}", "1234567891234567" );
I need to see Like This, 1234-5678-9123-4567;
Bu this Code does not work?
Can you help me?
That syntax takes an int, try this:
String.Format("{0:####-####-####-####}", 1234567891234567);
Edit: If you want to use this syntax on a string try this:
String.Format("{0:####-####-####-####}", Convert.ToInt64("1234567891234567"))
For ####-####-####-####, you will need a number. But you're feeding it a string.
It would be more practical to pad the string with additional zero's on the left so it becomes exactly 16 characters. Then insert the dash in three locations inside the string. Converting it to an Int64 will also work but if these strings become bigger or start to contain non-numerics, then you will have a problem.
string Key = "123456789012345";
string FormattedKey = Key.PadLeft(16, '0').Insert(12, "-").Insert(8, "-").Insert(4, "-");
That should be an alternative to formatting. It makes the key exactly 16 characters, then inserts three dashes from right to left. (Easier to keep track of indices.)
There are probably plenty of other alternatives but this one works just fine.

Categories