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
Related
Need to know of there is a way to use String.Format to remove leading characters from a string. I have a limitation in some existing code that I can only pass in a string and a format string for it.
So can you do something like
String.Format("Test output: {0:#}","001")
and produce the output
"Test output: 1"
I think the answer is 'No' but I wanted to make sure.
EDIT: To clarify, the format string will be put in a configuration file and the string to be formatted is a value coming out of a database. I can't execute any code on it. Has to be through the format string.
You could do it on the arg you are passing
String.Format("Test output: {0:#}", "001".TrimStart('0'))
Alternatively you could probably do a find with replace using a regular expression on the resulting string.
An other alternative is to define and pass in your own formatter using a custom implementation of IFormatProvider. I am not sure if this is allowed or not based your your last edit.
However, based on the restrictions listed, there is no way to do it with just the format string input
Okay, I have a string
string textToShow = "this\nrocks"
which when put in label in winforms window will then show
this
rocks
Which is the result I'd like to get. Now, instead of setting the textToShow in the code, I set it in the resource file. When I tried to get the value from resource file using
Properties.Resources.ResourceManager.GetString("textToShow");
the whole string instead will be treated as verbatim, showing
this\nrocks
when put in a label in a winforms window. This is not the result i'm looking for. What's the best way to store strings with special characters in resource file then? I can do string replace for every special characters, like
string.Replace(#"\n", "\n");
but then I need to replace every special characters whenever I call method ResourceManager.GetString, which I think is not the most elegant solution. If there is some ways to make string returned from method ResourceManager.GetString not verbatim, please do tell me.
Thanks
This was already answered here: StackOverflow: How to deal with newline
Basically you have two useful options:
Use shift + enter in the resource manager text editer to add a new line.
Or use String.Format() to replace {0} with \n on read.
The .Net 4.5 framework has the unescape functionality as shown here:
using System.Text.RegularExpressions;
Regex.Unescape(Properties.Resources.ResourceManager.GetString("textToShow"));
solves your issue. Now you can use \n and \u in the resource files.
On the resource editor type "this<shift+enter>rocks" as the resource value.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Parsing formatted string.
How can I use a String.Format format and transform its output to its inputs?
For example:
string formatString = "My name is {0}. I have {1} cow(s).";
string s = String.Format(formatString, "strager", 2);
// Call the magic method...
ICollection<string> parts = String.ReverseFormat(formatString, s);
// parts now contains "strager" and "2".
I know I can use regular expressions to do this, but I would like to use the same format string so I only need to maintain one line of code instead of two.
Here is some code from someone attempting a Scanf equivalent in C#:
http://www.codeproject.com/KB/recipes/csscanf.aspx
You'll have to implement it yourself, as there's nothing built in to do it for you.
To that end, I suggest you get the actual source code for the .Net string.format implmentation (actually, the relevant code is in StringBuilder.AppendFormat()). It's freely available, and it uses a state machine to walk the string in a very performant manner. You can mimic that code to also walk your formatted string and extract that data.
Note that it won't always be possible to go backwards. Sometimes the formatted string can have characters the match the format specifiers, making it difficult to impossible for the program to know what the original looked like. As I think about it, you might have better luck walking the original string to turn it into a regular expression, and then use that to do the match.
I'd also recommend renaming your method to InvertFormat(), because ReverseFormat sounds like you'd expect this output:
.)s(woc 2 evah .regarts si eman yM
I don't believe there's anything in-box to support this, but in C#, you can pass an array of objects directly to any method taking params-marked array parameters, such as String.Format(). Other than that, I don't believe there's some way for C# & the .NET Framework to know that string X was built from magic format string Y and undo the merge.
Therefore, the only thing I can think of is that you could format your code thusly:
object[] parts = {"strager", 2};
string s = String.Format(formatString, parts);
// Later on use parts, converting each member .ToString()
foreach (object p in parts)
{
Console.WriteLine(p.ToString());
}
Not ideal, and probably not quite what you're looking for, but I think it's the only way.
Is there a built method in .Net for C-style escaping of strings?
For example, I have to convert a string which contains quotes like "hello", and write it as an escaped string \"hello\".
Actually, to be more precise:
string original = "\"hello\"";
should be converted to
string what_i_need = "\\\"hello\\\"";
I could have probably done it myself while writing this question, but I don't want to reinvent hot water.
[Edit] According to the provided answer, this is actually a duplicate of: Can I convert a C# string value to a string literal. It didn't pop out since there were no tags and keywords I was looking for.
I dont think there is any built in methods. But if you have to write your own, Can I convert a C# string value to a string literal post maybe helpful
I have two strings read in from textfiles to compare and when I try to compare these files with winmerge or pspad, they both show as the same text strings. If I compare them with the following function, it fails:
string string1 = File.ReadAllText(#"c:\file1.txt");
string string2 = File.ReadAllText(#"c:\file2.txt");
bool stringMatch = false;
if (string1.Equals(string2, StringComparison.InvariantCulture)){
stringMatch = true;
}
//stringMatch is false here
After some searching it seems to be that a " and ' are different:
Content of file1.txt: é"'(§è!çà)-
Content of file2.txt: é”’(§è!çà)-
Any way I can properly compare these two strings and match those " & ' characters?
You could convert them both to byte[] using the methods under System.Text.Encoding
and then compare the byte[] arrays
It looks like you want to use the overload which takes StringComparison.
I'd guess given the current senario you want the "Ordinal" value but you may want one of the others depdending on what you are doing.
http://msdn.microsoft.com/en-us/library/system.stringcomparison.aspx
Well, you don't have the .NET strings in WinMerge or pspad, so something could well be going wrong while decoding. You need to explain your exact scenario:
Is the data in a file (hence WinMerge/pspad)?
How are you loading the file in .NET?
How are you loading the file in WinMerge etc?
EDIT: Okay, based on the comment - what is the encoding of the file meant to be? Are you specifying it in WinMerge anywhere? .NET will be using UTF-8 (because you haven't specified any other encoding).
After reading "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" you should be well equipped to solve your problem yourself.