4

What I have is a C# windows app that reads a bunch of SQL tables and creates a bunch of queries based on the results. What I'm having a small issue with is the final "," on my query

This is what I have

ColumnX,

from

I need to read the entire file, write out exactly what is in the file and just replace the last , before the from with nothing.

I tried .replace(@",\n\nfrom),(@"\n\nfrom) but it's not finding it. Any help is appreciated.

Example:

ColumnX,

from

Result:

ColumnX

from
1
  • 3
    Is that a String.Replace? If so you might want to try it without the @ symbols. Commented Mar 23, 2010 at 13:06

5 Answers 5

7

The line break is most likely the two character combination CR + LF:

.replace(",\r\n\r\nfrom","\r\n\r\nfrom")

If you want the line break for the current system, you can use the Environment.NewLine constant:

.replace(","+Environment.NewLine+Environment.NewLine+"from",Environment.NewLine+Environment.NewLine+"from")

Note that the @ in front of a string means that it doesn't use backslash escape sequences, but on the other hand it can contain line breaks, so you could write it in this somewhat confusing way:

str = str.replace(@",

from", @"

from");
Sign up to request clarification or add additional context in comments.

Comments

2

There are two solutions that you can try:

  1. Remove the @ symbol, as that means it's going to look for the literal characters of \n rather than a newline.
  2. Try .replace("," + Environment.NewLine + Environment.NewLine + from, Environment.NewLine + Environment.NewLine + "from)

1 Comment

+1, it was primarily the verbatim literal (@) that was screwing him up, other than there could be a space or CR in there as well
1

Instead of replacing or removing the comma when you read the file, it would probably be preferable to remove it before the file is written. That way you only have to bother with the logic once. As you are building your column list, just remove the last comma after the list is created. Hopefully you are in a position where you have control over that process.

Comments

1

If you can assume you always want to remove the last occurrence of the comma you can use the string function LastIndexOf to find the index for the last comma and use Remove from there.

myString = myString.Remove(myString.LastIndexOf(","), 1);

Comments

0

What about using Regex? Does that handle different forms of linefeed better?

var result = Regex.Replace(input, @",(\n*)from", "$1from");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.