简体   繁体   中英

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

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.

如果您可以假设您始终要删除最后一次出现的逗号,则可以使用字符串函数LastIndexOf查找最后一个逗号的索引并使用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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM