c# replace last character in every line - c#

How can I replace the last character in every line?
Example:
rtt45|20160706|N2413847|aneess kim|20160727|
rtt45|20160706|N2247673|ram thomus|20160729|
rtt45|20160706|N2373039|rohan kumar|20160721|
I have tried
string rr = "D:\\temp\\test_07272016020733.txt";
string lines = File.ReadAllText(rr);
lines =lines.Replace("| \n", "\n");

How about something like:
string rr = "D:\\temp\\test_07272016020733.txt";
string[] lines = File.ReadAllLines(rr);
lines = lines.Select(x => x.TrimEnd('|')).ToArray();
EDIT: If you want it all in a single string to end with:
var text = string.join(Environment.NewLine, lines);
For completeness, in a single line keeping variable names in tact:
string rr = "D:\\temp\\test_07272016020733.txt";
string lines = string.Join(Environment.NewLine, File.ReadLines(rr).Select(x => x.TrimEnd('|')));

replace
lines = lines.Replace("| \n", "\n");
with
lines = lines.Replace("|" + System.Environment.NewLine, System.Environment.NewLine);
or (equal)
lines = lines.Replace("|\r\n", "\r\n");

Related

Add a character on each line of a string

I make a CSV converter, for this, I need to replace all the spaces with ";". I have already did this step. The problem is that I have a texbox with the multiline mod. Here is my actual code :
string[] Espace1 = new string[] { " " };
foreach (string contenu in content1.Split(Espace1, StringSplitOptions.RemoveEmptyEntries))
{
content1 = content1.Replace(" ", ";");
File.WriteAllText(path1, content1);
}
Here is the output : (an example)
15;16;13;21
15;49;47
46;78;15
So that the file is well interprets like a csv I need to add a ";" at the end of each line. Like :
15;16;13;21;
15;49;47;
46;78;15;
Any help ? :)
EDIT
Here is my complete code :
string nom = tbxNom.Text;
#region Normal
try
{
string content1 = tbxArret.Text;
string path1 = #"C:\Users\DanyWin\Desktop\CsvOutput\" + nom + ".csv";
string[] Espace1 = new string[] { " " };
foreach (string contenu in content1.Split(Espace1, StringSplitOptions.RemoveEmptyEntries))
{
content1 = content1.Replace(" ", ";");
File.WriteAllText(path1, content1);
}
}
catch
{
lblInfo.Text = "Erreur";
}
content1 seems to contain the whole file.
So if you want to add semicolons to each line, you could replace the newline with a semicolon and a newline.
content1 = content1.Replace("\n", ";\n");
You can make your code a bit easier:
string nom = tbxNom.Text;
#region Normal
try
{
string content1 = tbxArret.Text;
string path1 = #"C:\Users\DanyWin\Desktop\CsvOutput\" + nom + ".csv";
var lines = content1.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Select(line => Regex.Replace(line, #"\s+", ";") + ";");
content1 = String.Join("\n", lines);
File.WriteAllText(path1, content1);
}
catch
{
lblInfo.Text = "Erreur";
}
content1 = string.Concat( content1.Replace(" ", ";"), ";");
Remove all spaces then concat ";" at end
char []split = new char[]{' '};
//replaces all " " with ";", contiguous " " will be replaced with a single ";"
var c2 = String.Join(";", content1.Split(split, StringSplitOptions.RemoveEmptyEntries));
//replaces all newlines with a semicolon followed by a newline, thus appends a semicolon to the end of line.
var c3 = c2.Replace(System.Environment.NewLine, ";"+System.Environment.NewLine);
//If the file did not end with an NewLine, append a semicolon to the last line
if (!c3.EndsWith(System.Environment.NewLine)) c3+=";";
File.WriteAllText(path, c3);
It's not the fastest solution, but it works.

Adding a newline into a string from text file

I have a text file.
I need to add a newline after every new line from text and put every new line surrounded by "" or //.
My Output should be like this:
//Name Disengagement point//
//Description Automated test case to record
disengagement point and force-travel characteristic needed for the
point.//
//StartRecording ForceTravel//
//UserInteraction Please, start attempting to shift the gear to 1st gear.//
//Capture DisengagementPoint UserInput == 1 PressClutch 1 UserInput == 1//
//UserInteraction Please, shift the gear to neutral.//
//ReleaseClutch 100 ForceTravel == LimitReleased//
The method for reading text file:
if (!File.Exists(measurementPath))
{
string[] readText = File.ReadAllLines(measurementPath);
foreach (string s in readText)
{
script = s.Replace(" ", " // ");
char[] separator = new char[] { ' ' };
String[] fields = s.Split(separator);
You can use File.ReadLines, LINQ + String.Format and File.WriteAllLines:
var newLines = File.ReadLines(measurementPath)
.Select(line => String.Format("//{0}//", line))
.ToList();
File.WriteAllLines(measurementPath, newLines);

RichTextBox not printing newline

I have this method that replaces(in bold) some words in a string and show the changed string in a ritchtextBox.
In the final string I need to replace the # symbol by a newline.
I already tried checked this forum tying several solutions, but nothing worked.
The method I use is
private string bold(string ing)
{
StringBuilder builder = new StringBuilder();
ing = " " + ing + " ";
builder.Append(#"{\rtf1\ansi");
foreach (string word in splitwords)
{
var regex = new Regex(#"(?<![\w])" + word + #"(?![\w])", RegexOptions.IgnoreCase);
ing = regex.Replace(ing, m => #"\b" + m.ToString() + #"\c0");
}
ing = ing.Replace(#"\b", #"\b ");
ing = ing.Replace(#"\c0", #" \b0");
ing = ing.Replace("#", Environment.NewLine);
builder.Append(ing);
builder.Append(#"}");
MessageBox.Show("builder.ToString():" + builder.ToString());
return builder.ToString();
}
When I call the this method and "put it" in the ritchTextBox it doesn´t print the new line
ingred.Rtf = bold(ingd);
How should I solve this??
EDIT:: input string - line1 # line2 # line3
output in the MessageBox
Builder.ToString() : {\rtf1\ansi\b line1\b0
line2
line3
}
output in the ritchTextBox: line1 line2 line3
Instead of
ing = ing.Replace("#", Environment.NewLine);
Try
ing = ing.Replace("#", #"\par\r\n");
Use This Code For Repalce
int startIndex = 0, index;
RichTextBox myRtb = new RichTextBox(); // if have A richtextBox Remove thisline and Use your Richtextbox
myRtb.Rtf = STRRTF;// if have A richtextBox Remove thisline and Use your Richtextbox
while ((index = myRtb.Text.IndexOf("#", startIndex)) != -1)
{
myRtb.Select(index, word.Length);
myRtb.SelectedText ="\n";
startIndex = index + 1;
}
Better use Environment.NewLine for adding new line also Make sure yourRTB.MultiLine property is set to true. assign string to richtext box like this yourRTB.AppendText(t)
Try replacing it with a "\r\n" character sequence?
edit: is MultiLine property of ritchtextBox enabled?

How can i delete space from text file and replace it semicolon?

I have this data into the test text file:
behzad razzaqi xezerlooot abrizii ast
i want delete space and replace space one semicolon character,write this code in c# for that:
string[] allLines = File.ReadAllLines(#"d:\test.txt");
using (StreamWriter sw = new StreamWriter(#"d:\test.txt"))
{
foreach (string line in allLines)
{
if (!string.IsNullOrEmpty(line) && line.Length > 1)
{
sw.WriteLine(line.Replace(" ", ";"));
}
}
}
MessageBox.Show("ok");
behzad;;razzaqi;;xezerlooot;;;abrizii;;;;;ast
but i want one semicolon in space.how can i solve that?
Regex is an option:
string[] allLines = File.ReadAllLines(#"d:\test.txt");
using (StreamWriter sw = new StreamWriter(#"d:\test.txt"))
{
foreach (string line in allLines)
{
if (!string.IsNullOrEmpty(line) && line.Length > 1)
{
sw.WriteLine(Regex.Replace(line,#"\s+",";"));
}
}
}
MessageBox.Show("ok");
Use this code:
string[] allLines = File.ReadAllLines(#"d:\test.txt");
using (StreamWriter sw = new StreamWriter(#"d:\test.txt"))
{
foreach (string line in allLines)
{
string[] words = line.Split(" ", StringSplitOptions.RemoveEmptyEntries);
string joined = String.Join(";", words);
sw.WriteLine(joined);
}
}
You need to use a regular expression:
(\s\s+)
Usage
var input = "behzad razzaqi xezerlooot abrizii ast";
var pattern = "(\s\s+)";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, ';');
You can do that with a regular expression.
using System.Text.RegularExpressions;
and:
string pattern = "\\s+";
string replacement = ";";
Regex rgx = new Regex(pattern);
sw.WriteLine(rgx.Replace(line, replacement));
This regular expression matches any series of 1 or more spaces and replaces the entire series with a semicolon.
you can try this
Regex r=new Regex(#"\s+");
string result=r.Replace("YourString",";");
\s+ is for matching all spaces. + is for one or more occurrences.
for more information on regular expression see http://www.w3schools.com/jsref/jsref_obj_regexp.asp
You should check a string length after replacement, not before ;-).
const string file = #"d:\test.txt";
var result = File.ReadAllLines(file).Select(line => Regex.Replace(line, #"\s+", ";"));
File.WriteAllLines(file, result.Where(line => line.Length > 1));
...and don't forget, that for input hello you will get ;hello;.

Exception "String cannot be of Zero length"

We are trying to read each word from a text file and replace it with another word.
For smaller text files, it works well. But for larger text files we keep getting the exception: "String cannot be of zero length.
Parameter name: oldValue "
void replace()
{
string s1 = " ", s2 = " ";
StreamReader streamReader;
streamReader = File.OpenText("C:\\sample.txt");
StreamWriter streamWriter = File.CreateText("C:\\sample1.txt");
//int x = st.Rows.Count;
while ((line = streamReader.ReadLine()) != null)
{
char[] delimiterChars = { ' ', '\t' };
String[] words = line.Split(delimiterChars);
foreach (string str in words)
{
s1 = str;
DataRow drow = st.Rows.Find(str);
if (drow != null)
{
index = st.Rows.IndexOf(drow);
s2 = Convert.ToString(st.Rows[index]["Binary"]);
s2 += "000";
// Console.WriteLine(s1);
// Console.WriteLine(s2);
streamWriter.Write(s1.Replace(s1,s2)); // Exception occurs here
}
else
break;
}
}
streamReader.Close();
streamWriter.Close();
}
we're unable to find the reason.
Thanks in advance.
When you do your string.Split you may get empty entries if there are multiple spaces or tabs in sequence. These can't be replaced as the strings are 0 length.
Use the overload that strips empty results using the StringSplitOptions argument:
var words = line.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
The exception occurs because s1 is an empty string at some point. You can avoid this by replacing the line
String[] words = line.Split(delimiterChars);
with this:
String[] words = line.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
You want to change your Split method call like this:
String[] words = line.Split(delimiterChars,StringSplitOptions.RemoveEmptyEntries);
It means that s1 contains an empty string ("") which can happen if you have two consecutive white spaces or tabs in your file.

Categories

Resources