Add a character on each line of a string - c#

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.

Related

Split and Append "AND" between values

how to split below value and append AND between values ?
I cannot Split with Space as there is spaces between words
"\"Mark John\" \"Tina Roy\""
as
"\"Mark John\" AND \"Tina Roy\""
In the end it should look like -
"Mark John" AND "Tina Roy"
Any help is appreciated.
string operatorValue = " AND ";
if (!string.IsNullOrEmpty(operatorValue))
{
foreach (string searchVal in SearchRequest.Text.Split(' '))
{
if (!string.IsNullOrEmpty(searchVal))
searchValue += searchVal + operatorValue;
}
}
int index = searchValue.LastIndexOf(operatorValue);
if (index != -1)
{
outputSearchValue = searchValue.Substring(0, index);
}
Try
var result = str.Replace("\" \"","\" And \"");
If you have more than one name, or there is a possibility that you could have more than one whitespace between two names, you could opt for Regex.
var result = Regex.Replace(str,"\"\\s+\"","\" And \"");
Example,
var str = "\"Mark John\" \"Tina Roy\" \"Anu Viswan\"";
var result = Regex.Replace(str,"\"\\s+\"","\" And \"");
Output
"Mark John" And "Tina Roy" And "Anu Viswan"
Or use Regular Expressions:
var test = "\"John Smith\" \"Bill jones\" \"Bob Norman\"";
Console.WriteLine(Regex.Replace(test, "\" \"", "\" AND \""));
Instead of splitting, replace the " " with " AND "
var test = "\"Mark John\" \"Tina Roy\"";
var new_string= test.Replace("\" \"", " AND ");

c# replace last character in every line

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

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?

Removing multiple instances of words from a single set in a string

I have a string street that may contains:
street= "Siegfriedst strasse st 16.";
street= "Frontos strasse s .";
I want to remove the extra "st", "strasse" and "s".
I used:
street= street.Replace("(", "").Replace(")", "").Replace(".", "").
Replace("-", "").Replace("strasse","").
Replace("st","").Replace("s","");
But I don't want to remove "st" from "Siegfriedst" and "s" from "Frontos".
Perhaps this is what you want, it's not clear if you only want to remove duplicate words or sub-strings:
public static string RemoveDuplicates(string input, params string[] wordsToCheck)
{
var wordSet = new HashSet<string>(wordsToCheck);
int taken = 0;
var newWords = input.Split()
.Select(w => !wordSet.Contains(w) || ++taken == 1 ? w : "");
return string.Join(" ", newWords);
}
Usage:
string text = RemoveDuplicates("Siegfriedst strasse st 16.", "st", "strasse", "s");
Result: Siegfriedst strasse 16.
street = street.Replace(".", " ") //To better enable pattern matching
.Replace(" strasse ", "")
.Replace(" st ", " ")
.Replace(" s ", "")
.Replace(" ", " ")
.Trim(); //Trim() removes the leading and trailing whitespaces
street = street.Replace("(", "")
.Replace(")", "")
.Replace(".", "")
.Replace("-", "")
.Replace(" strasse "," ")
.Replace(" st "," ")
.Replace(" s "," ");
You can write a helper method like:
public static string Cleanup(string text, string[] exclude)
{
string[] parts = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
List<string> words = new List<string>();
foreach(string part in parts)
{
if (!exclude.Contains(part))
{
words.Add(part);
}
}
return string.Join(" ", words.ToArray());
}
and then use it like:
string street = Cleanup("Siegfriedst strasse st 16.", new string[] { "strasse", "st", "s", " " });
You can use regular expressions. This will match whole words "strasse" "st" or "s", but not in parts of words:
using System.Text.RegularExpressions;
Regex rgx = new Regex(#"\b(strasse|st|s)\b|\(|\)|\.");
street = rgx.Replace(street, "");
Based on the fact that you used concatenated Replace operations (thus not wanting any of the extra strings to appear) I would suggest the following LINQ query:
street = street.Split(' ').Where(s => s != "strasse" && s != "st" && s != "s").Aggregate((x, y) => x + " " + y);

String Cleaning in C#

I am trying to write a function that as input takes a string containing words and removes all single character words and returns the new string without the removed characters
E.g.:
string news = FunctionName("This is a test");
//'news' here should be "This is test".
Can you please help?
Obligatory LINQ one-liner:
string.Join(" ", "This is a test".Split(' ').Where(x => x.Length != 1).ToArray())
Or as a nicer extension method:
void Main()
{
var output = "This is a test".WithoutSingleCharacterWords();
}
public static class StringExtensions
{
public static string WithoutSingleCharacterWords(this string input)
{
var longerWords = input.Split(' ').Where(x => x.Length != 1).ToArray();
return string.Join(" ", longerWords);
}
}
I'm sure there's a nicer answer using regex, but you could do the following:
string[] words = news.Split(' ');
StringBuilder builder = new StringBuilder();
foreach (string word in words)
{
if (word.Length > 1)
{
if (builder.ToString().Length ==0)
{
builder.Append(word);
}
else
{
builder.Append(" " + word);
}
}
}
string result = builder.ToString();
The interesting thing about this question is that presumably you also want to remove one of the spaces surrounding the single-letter word.
string[] oldText = {"This is a test", "a test", "test a"};
foreach (string s in oldText) {
string newText = Regex.Replace(s, #"\s\w\b|\b\w\s", string.Empty);
WL("'" + s + "' --> '" + newText + "'");
}
Output...
'This is a test' --> 'This is test'
'a test' --> 'test'
'test a' --> 'test'
With Linq syntax, you could do something like
return string.Join(' ', from string word in input.Split(' ') where word.Length > 1))
string str = "This is a test.";
var result = str.Split(' ').Where(s => s.Length > 1).Aggregate((s, next) => s + " " + next);
UPD
Using the extension method:
public static string RemoveSingleChars(this string str)
{
return str.Split(' ').Where(s => s.Length > 1).Aggregate((s, next) => s + " " + next);
}
//----------Usage----------//
var str = "This is a test.";
var result = str.RemoveSingleChars();

Categories

Resources