C # Reading a file and writing a replacement string

I have a Windows C # application that reads a bunch of SQL tables and creates a bunch of queries based on the results. I have a little problem with the last "," at my request

This is what I have

ColumnX, from 

I need to read the whole file, write out exactly what is in the file, and just replace the last one, and then with nothing.

I tried .replace(@",\n\nfrom),(@"\n\nfrom) , but did not find it. Any help is appreciated.

Example:

 ColumnX, from 

Result:

 ColumnX from 
+4
source share
5 answers

A line break most likely consists of two combinations of CR + LF characters:

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

If you want to split the string 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 the line means that it does not use backslash escape sequences, but on the other hand, it may contain line breaks, so you can write it in this somewhat confusing way:

 str = str.replace(@", from", @" from"); 
+7
source

There are two solutions you can try:

  • Remove the @ character, as this means that it will look for the alphabetic characters \n , not a newline.
  • Try .replace("," + Environment.NewLine + Environment.NewLine + from, Environment.NewLine + Environment.NewLine + "from)
+2
source

Instead of replacing or removing the comma when you read the file, it would probably be preferable to delete it before the file is written. Thus, you only need to worry once with the logic. When you create your list of columns, just remove the last comma after creating the list. I hope you are in a position where you have control over this process.

+1
source

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

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

How about using regex? Does this support various forms of line feeds better?

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

0
source

Source: https://habr.com/ru/post/1304871/


All Articles