C# string formatting with variable space alignment - c#

I want to do something like
String.Format("Completed {0:9} of ",0) + xlsx.totalCount.ToString();
except instead of hardcoding a 9 I want the alignment to be whatever xlsx.totalCount is. Any thoughts?

Try it like this:
string formatString = "{0:" + xlsx.totalCount.ToString() + "}";
String.Format("Completed " + formatString + " of ", 0) + xlsx.totalCount.ToString();

The string doesn't have to be a compile time constant, you can build the string during runtime (using a StringBuilder, operator+ or even a nested String.Format).
This, for instance will produce the needed string with xlsx.totalCount replacing the "9":
String.Format("Completed {0:" + xlsx.totalCount + "} of "...

I'd assumed that he wanted a count of 9s depending on the value of xlsx.totalCount.
StringBuilder sb = new StringBuilder();
sb.Append( '9', xlsx.totalCount );
String.Format( "Completed {0:" + sb.ToString() + "} of ",0) + xlsx.totalCount.ToString();
Again, there feels like there should be an easier way of building a chain of 9s, but not in 3 minutes of thinking, apparently.

Related

QueryString is taking first substring and discarding rest post space

I have a query string which passes 6 parameters in C# as shown below
string url = "Report.aspx?Desc=" + Desc.SelectedValue + "&PON=" + PNumber.Text + "&InsNme=" + ins.ToUpper().ToString() + "&BackTy=" + cb.SelectedValue + "&StartDate=" + txtDate.Text + "&EndDate=" + txtTodate.Text + "&Name=" + nme;
string s = "window.open('" + url + "', 'popup_window', 'width=1500,height=800,left=200,top=150,resizable=yes');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
Now, in the above string InsNme contains a value of John Patrice Joanne. Instead of complete value of InsNme Report.aspx contains just John. How to handle this?
The spaces in the name are breaking the URL.
If you want to do it yourself, replace spaces with %20. Otherwise a simple, but not anywhere near "good" technique is:
url = "Report.aspx?";
// for each name value pair ...
url += dataLabel + "=" + System.Web.HttpUtility.UrlEncode( dataChunk ) +"&";
The utility is preferred as it will take care of other, similar issues such as literal '&' in a name.
Check this answer for better solutions.
How to build a query string for a URL in C#?

C# String Interpolation Variable Alignment [duplicate]

I want to do something like
String.Format("Completed {0:9} of ",0) + xlsx.totalCount.ToString();
except instead of hardcoding a 9 I want the alignment to be whatever xlsx.totalCount is. Any thoughts?
Try it like this:
string formatString = "{0:" + xlsx.totalCount.ToString() + "}";
String.Format("Completed " + formatString + " of ", 0) + xlsx.totalCount.ToString();
The string doesn't have to be a compile time constant, you can build the string during runtime (using a StringBuilder, operator+ or even a nested String.Format).
This, for instance will produce the needed string with xlsx.totalCount replacing the "9":
String.Format("Completed {0:" + xlsx.totalCount + "} of "...
I'd assumed that he wanted a count of 9s depending on the value of xlsx.totalCount.
StringBuilder sb = new StringBuilder();
sb.Append( '9', xlsx.totalCount );
String.Format( "Completed {0:" + sb.ToString() + "} of ",0) + xlsx.totalCount.ToString();
Again, there feels like there should be an easier way of building a chain of 9s, but not in 3 minutes of thinking, apparently.

What is the better way to string format a double quote if the element inside the quote is a variable?

I have made a code like this:
TextWriter tw = File.CreateText(#"D:\output.txt");
tw.Write(#"{""lon"":" + grid.point[0].ToString("###.####") + ",");
tw.Write(#"""latt"":" + grid.point[1].ToString("###.####") + ",");
char c = '"';
////improve the last line pls
tw.Write(#"""color"":" + c.ToString() + "#" + grid.Color.ToString("X").Substring(2) + c.ToString() + "},\n");
With the above code, I had successfully made a JSON format look like below:
{"lon":121,"latt":40.5025,"color":"#3EC1FF"},
Now My question is:
How to improve the string format without using the c.toString()?
You can use the format overload of the Write method e.g. Write(String, Object[]).
Something like this:
tw.Write("\"color\":\"#{0}\"}},\n", grid.Color.ToString("X").Substring(2));
StringBuilder jsonBuilder=new StringBuilder();
jsonBuilder.AppendFormat("{0}", "{");
jsonBuilder.AppendFormat("\"Lat\":{0:0.000},", 584.25689);
jsonBuilder.AppendFormat("\"Lon\":{0:0.000},", 784.25689);
jsonBuilder.AppendFormat("Color:{0}","\"#3EC1FF\"");
jsonBuilder.AppendFormat("{0}", "}");
string json = jsonBuilder.ToString();

String.Replace Not modifying my String

I am trying to save a number of images and I'd like to use the DateTime to have distinct and identifiable Filenames.
So I create a String with the correct Path, add the datetime to it and remove the spaces, dots and colons.
String imagePath = "D:\\Patienten\\" + username;
imagePath += "\\"+DateTime.Now.ToString();
Console.WriteLine("WithFilename: " + imagePath);
imagePath.Replace(" ", "");
Console.WriteLine("Without \" \" : " + imagePath);
imagePath.Replace(".", "");
Console.WriteLine("Without \".\": " + imagePath);
imagePath.Replace(":", "");
Console.WriteLine("Output format: " + imagePath);
imagePath += ".png";
image.Save(imagePath);
According to the console output the String doesnt change at all.
Meaning all the Output Strings from Console.Writeline are identical.
I am using c# in visual Studio Express 2010 in case that makes a difference.
Can anyone find an Error here?
Thanks in advance!
Strings are immutable, the modified string will be a new string that is returned from the function
e.g.
imagePath = imagePath.Replace(" ", "");
Why strings are immutable
Why not just use DateTime.ToString() with a format and drop the dividers using that? Would be more efficient than performing several String.Replace() yourself:
string imagePath = "D:\\Patienten\\" + username + "\\" + DateTime.Now.ToString("yyyyMMdd hhmmssfff") + ".png";
You should use:
imagePath = imagePath.Replace(" ", ""); You should assign returned value
From the documentation (emphasis mine):
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
It is supposed to work like that. Use
imagePath = imagePath.Replace(" ", "");
instead.

How can I elegantly implement multiple string replacements in the same file?

Currently I have some code to replace strings in a file that looks like this:
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
"( " + column.Key + " )",
" " + column.Value + " "
));
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
"(\\[\"" + column.Key + "\"\\])",
"[\"" + column.Value + "\"]"
));
However, each replacement opens and closes the file, and it seems that occasionally they run "too fast" and one replacement will not work because the file did not close yet in a previous string replacement. Is there any code I can reuse that solves this issue, perhaps using the FileStream class (so I can open and close once)? Or suggestions on a better way to do this? Just wondering if there is something simpler I can do than having to create byte arrays of the strings I want to replace and writing code to read, write, and seek through bytes manually. Thanks.
A better practice would be to read the contents of the file once, storing it into a local variable. Then performing any changes you need (in your case, two regular expressions), and then writing that output to the file. File IO is one of the most expensive operations a computer can perform, and in-memory computation is much cheaper. Hit the disk as little as possible, as long as you can avoid it.
Well, I'd use:
string text = File.ReadAllText(filePath);
text = Regex.Replace(...);
text = Regex.Replace(...);
...
File.WriteAllText(filePath, text);
I'm still surprised to hear that the original code didn't work though. It wasn't pleasant in terms of multiple writes and reads, but I'd have expected it to work.
string contents = File.ReadAllText(filePath);
contents = Regex.Replace(contents,
"( " + column.Key + " )",
" " + column.Value + " ");
contents = Regex.Replace(contents,
"(\\[\"" + column.Key + "\"\\])",
"[\"" + column.Value + "\"]");
File.WriteAllText(filePath, contents);
Sounds like you should be doing your all your string replacements on a string residing in memory, then write your final resulting string to disk.
var fileContents = File.ReadAllText(filePath);
fileContents = Regex.Replace(fileContents,
"( " + column.Key + " )",
" " + column.Value + " "
);
fileContents = Regex.Replace(fileContents ,
"(\\[\"" + column.Key + "\"\\])",
"[\"" + column.Value + "\"]"
);
File.WriteAllText(filePath, fileContents);
Well, the simlest method would be to ReadAllText, do your replacements and then WriteAllText.
var text = File.ReadAllText(filePath);
text = Regex.Replace(text,"( " + column.Key + " )"," " + column.Value + " ");
text = Regex.Replace(text,"(\\[\"" + column.Key + "\"\\])","[\"" + column.Value + "\"]");
File.WriteAllText(text,filePath);

Categories

Resources