my code adding semicolon to end of each line... But I need closing ) parenthesis on my second sentence on richtextbox1. how can I add correctly?
NOT: my second sentence can end with any word, which means succession s.Endwith("no") replace ("no",");").....not a option to use!.
My code only puts ; end of each line
string[] lines = richTextBox1.Lines;
List<string> ToAdd = new List<string>();
string filter = ")";
foreach (string s in lines)
{
string hold = s;
if (s.EndsWith(")"))
hold = s.Replace(filter, ";");
}
richTextBox1.Lines = ToAdd.ToArray();
My Result
This is my sentence (Yes);
This is my sentence (Yes) or no;
This is my sentence (Yes);
This is my sentence (Yes);
I want this result:
This is my sentence (Yes);
This is my sentence (Yes) or no);
This is my sentence (Yes);
This is my sentence (Yes);
Try following:
OracleDataReader reader = Command.ExecuteReader())
{
reader.Read();
string[] split = reader[0].ToString().Trim().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in split)
{
if(line.Trim()==")")
richTextBox1.AppendText(line.Trim() + ";" + Environment.NewLine);
else
richTextBox1.AppendText(line.Trim() + Environment.NewLine);
}
}
Edit:
Before for loop, try following:
if(reader[0].toString()==")")
reader[0].append(";")
(Not exactly the same, but can continue with this logic)
Related
I need to remove words from the text with separators next to them. The problem is that the program only removes 1 separator after the word but there are many of them. Any suggestions how to remove other separators?
Also, I need to make sure that the word is not connected with other letters. For example (If the word is fHouse or Housef it should not be removed)
At the moment I have:
public static void Process(string fin, string fout)
{
using (var foutv = File.CreateText(fout)) //fout - OutPut.txt
{
using (StreamReader reader = new StreamReader(fin)) // fin - InPut.txt
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] WordsToRemove = { "Home", "House", "Room" };
char[] seperators = {';', ' ', '.', ',', '!', '?', ':'};
foreach(string word in WordsToRemove)
{
foreach (char seperator in seperators)
{
line = line.Replace(word + seperator, string.Empty);
}
}
foutv.WriteLine(line);
}
}
}
}
I have :
fhgkHouse!House!Dog;;;!!Inside!C!Room!Home!House!Room;;;;;;;;;;!Table!London!Computer!Room;..;
Results I get:
fhgkDog;;;!!Inside!C!;;;;;;;;;!Table!London!Computer!..;
The results should be:
fhgkHouse!Dog;;;!!Inside!C!Table!London!Computer!
Try this regex : \b(Home|House|Room)(!|;)*\b|;+\.\.;+
See at: https://regex101.com/r/LUsyM8/1
In there, I substitute words and special characters with blank or empty string.
It produces the same expected result I guess.
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);
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;.
If I've got a string:
How much wood would a woodchuck chuck
if a woodchuck could chuck wood?
Just as much as a woodchuck would
if a woodchuck could chuck wood.
and I want to replace these words with "":
wood, chuck, if
and this is my code:
string[] words = new string[] { "wood", "chuck", "if" };
string input = woodchuckText;
string output = string.Empty;
foreach (string word in words)
{
output = input.Replace(word, string.Empty);
}
Console.Write(output);
why it only replaces the last word instead of replacing them all?
input never changes after the replacement, so basically the output you are getting is the same as if you only replaced the last of your words.
To resolve this, do this instead:
output = input;
foreach (string word in words)
{
output = output.Replace(word, string.Empty);
}
because you are iterating always on the original copy of Input and in last iteration only the last replace will take effect and hence you got the output result
foreach (string word in words)
{
input = input.Replace(word, string.Empty);
}
output = input;
Hint
try for example to put a breakpoint on output = input.Replace(word, string.Empty); by pressing F9 and u will see what's the output
or
just place Console.Write(output); in the foreach loop
foreach (string word in words)
{
output = input.Replace(word, string.Empty);
Console.Write(output);
}
You can also use regular expression:
string[] words = new string[] { "wood", "chuck", "if" };
var output = Regex.Replace(input, String.Join("|", words), "");
Because each iteration you are setting the output to the original input string. Therefore only the last iteration will be set on output. Adjust logic to keep updating the same string:
string[] words = new string[] { "wood", "chuck", "if" };
string input = woodchuckText;
string output = input;
foreach (string word in words)
{
output = output.Replace(word, string.Empty);
}
Console.Write(output);
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.