开发者

C# Reading a file and writing out replacing string

What I have is a C# windows app that reads a bunch of SQL tables and creates a bunch of queries base开发者_开发技巧d 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


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");


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)


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.


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);


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜