1

I am trying to split some string on the basis of newline character '\n'

I have this delimiter stored in resx file as:

Name: RecordDelimiter
Value: \n

When I retrieve this value from .resx file it is always returned as '\n' and split function does not return accurate results.
However when I try with string "\n", it's working fine

Here is my code -

private static void GetRecords()
{
    string recordDelimiter = @"\n";
    string recordDelimiter1 = "\n"; // only this returns correct result
    string recordDelimiter2 = ResourceFile.RecordDelimiter; //from resx file, returns \\n :-(
    string recordDelimiter3 = ResourceFile.RecordDelimiter.Replace("\\", @"\"); //try replacing \\n with \n

    string fileOutput = "aaa, bbb, ccc\naaa1, bbb1, ccc1\naaa2, bbb2, ccc2";

    string[] records = fileOutput.Split(new string[] { recordDelimiter }, StringSplitOptions.None);
    string[] records1 = fileOutput.Split(new string[] { recordDelimiter1 }, StringSplitOptions.None);
    string[] records2 = fileOutput.Split(new string[] { recordDelimiter2 }, StringSplitOptions.None);
    string[] records3 = fileOutput.Split(new string[] { recordDelimiter3 }, StringSplitOptions.None);

    int recordCount = records.Count();  //returns 1
    int recordCount1 = records1.Count();  //returns 3 -- only this returns correct result
    int recordCount2 = records2.Count();  //returns 1
    int recordCount3 = records3.Count();  //returns 1
}

I want to keep the delimiter in resx file.
Can anyone please guide if I am missing something?

Thank you!

4

1 回答 1

1

The reason your second method is the only one returning the correct result is that it is the only one where the delimiter is the new line character. "\n" is just a representation of the newline character in C#, and @"\n" is the literal string of a slash followed by the letter n. In other words @"\n" != "\n".

So if you wanted to store the delimiter character in resx, you would need to show us the code of how you are storing it there. Currently it seems to just be stord as a literal string, and not the actual control characters.

One (very rough) fix would be to take the string from the Resources and call .Replace(@"\n", "\n") depending on what exactly is stored in the file. I will update my answer if/when I find a better solution, or once you have updated your question.

EDIT:

Ok, found a somewhat gimmicky solution. The core problem is how do you write just \n, correct? Well, I made a test project, with a textbox and the following code:

this.textBox1.Text = "1\n2";

Fire up this project, select all of the text in the textbox, and copy to clipboard. Then go to your real project's resources, and paste the value from your clipboard. Then carefully delete the numbers from around the control character. And there you go, \n control character in a resource string. (The reason for the numbers was that it wasn't possible to select only the control character from the textbox.)

于 2012-08-09T12:18:11.610 回答