adding line break - c#

I have a problem with adding line break in a string. I have tried using "\r\n", and Environment.NewLine also does not work.
FirmNames = "";
foreach (var item in FirmNameList)
{
if (FirmNames != "")
{
FirmNames += ", " + LineBreak; -- I want a line break here after the comma ","
}
FirmNames += item;
}
Can anyone help?

The correct answer is to use Environment.NewLine, as you've noted. It is environment specific and provides clarity over "\r\n" (but in reality makes no difference).
foreach (var item in FirmNameList)
{
if (FirmNames != "")
{
FirmNames += ", " + Environment.NewLine;
}
FirmNames += item;
}

Give this a try.
FirmNames = String.Join(", \n", FirmNameList);

C# 6+
In addition, since c#6 you can also use a static using statement for System.Environment.
So instead of Environment.NewLine, you can just write NewLine.
Concise and much easier on the eye, particularly when there are multiple instances ...
using static System.Environment;
...
foreach (var item in FirmNameList)
{
if (FirmNames != "")
{
FirmNames += ", " + NewLine;
}
FirmNames += item;
}

This worked for me:
foreach (var item in FirmNameList){
if (FirmNames != "")
{
FirmNames += ",\r\n"
}
FirmNames += item;
}

Try using \n when concatenating strings, as in this example:
var name = "Raihan";
var ID = "1234";
Console.WriteLine(name + "\n" + ID);

\n in c3 working correctly
using System;
namespace testing2
public class Test {
public static void Main(string[] args) {
Console.WriteLine("Enter your name");
String s = Console.ReadLine();
Console.WriteLine("Your name is " + s + "\n" + "Thank You");
}
}

There are many ways to do it, in my case I use several because some don't work on the platform I need, you can try the following:
Environment.NewLine //--> recommendable
\n
\r
\n\r
\r\n

3 WAYS TO INSERT A NEW LINE IN C#
1:
Console.WriteLine("This is a line");
Console.WriteLine();
Console.WriteLine("This is another line");
2:
Console.WriteLine("This is a line.\nThis is another line.");
3:
Console.WriteLine("This is a line." + Environment.NewLine + "This is another line.");

string[] abcd = obj.show();
Response.Write(string.join("</br>", abcd));

Related

Text editing small program

The program should return edit text, where you have to replace" - ", ": ", "; ", ", ", " " with "\t".
The problem here is the result
Input: Китай: 1405023000; 24.08.2020; 17.99%
Expected Китай 1405023000 24.08.2020 17.99%
Myne Китай: 1405023000; 24.08.2020; 17.99%
So for some reason, I believe he messing with the order of `stringSeparators` elements or what. I am interested in this moment
public static string ReplaceIncorrectSeparators(string text)
{
string populationEdited = "";
string[] stringSeparators = new string[] {" - ", ": ", "; ", ", ", " "};
for (int i = 0; i < stringSeparators.Length; i++)
{
populationEdited = text.Replace(stringSeparators[i], "\t");
}
return populationEdited;
}
I've already solved the problem in another way but I want to solve it with separators.
The main problem in your code is that it doesn't store the result of Replace properly. This should do the trick:
public static string ReplaceIncorrectSeparators(string text)
{
string populationEdited = text; // You need to start with the original
string[] stringSeparators = new string[] {" - ", ": ", "; ", ", ", " "};
for (int i = 0; i < stringSeparators.Length; i++)
{
// And here instead of text.Replace you do populationEdited.Replace
populationEdited = populationEdited.Replace(stringSeparators[i], "\t");
}
return populationEdited;
}
You could Regex as an alternative. It would make your code shorter (an in my opinion more readable).
public static string ReplaceIncorrectSeparators(string text)
{
Regex regex = new Regex(#" - |: |; |, | ");
return regex.Replace(text, "\t");
}

Overwrite/delete contents of a text file in c# .net

I'm making a program that writes a list of student objects to a text file and needs to be saved, I could either simply overwrite the contents of the file or delete the contents and rewrite the new list. This is the code I've tried using after some searching,
private void saveTSMI_Click(object sender, EventArgs e)
{
if (lstStudNames.Items.Count != 0)
{
SaveFileDia.Filter = "Text Files | *.txt";
if (SaveFileDia.ShowDialog() == DialogResult.OK)
{
//Clear the file
File.WriteAllText(SaveFileDia.FileName, string.Empty);
//Put all the student info into a string
foreach (Stud student in StudentList)
{
StudentInfoHolder += "Name: " + student.Name + Environment.NewLine +
"Subject: " + student.Subject + Environment.NewLine +
"Age: " + student.age + Environment.NewLine +
"Grade: " + student.Grade + Environment.NewLine
+ Environment.NewLine;
}
Clipboard.SetText(StudentInfoHolder);
File.WriteAllText(SaveFileDia.FileName, StudentInfoHolder);
}
}
else
{
MessageBox.Show("Nothing to save");
}
I've seen that File.WriteAllText() is meant to overwrite the file but nothing is overwritten when the program is saved.
You have to either reset the StudentInfoHolder class member before the foreach loop, or even better, use a local string variable in combination with String.Format method like this:
string studentInfoHolder;
foreach (Stud student in StudentList)
{
studentInfoHolder +=
string.Format("Name: {0}\r\nSubject: {1}\r\nAge: {2}\r\nGrade: {3}",
student.Name, student.Subject, student.age, student.Grade);
}
File.WriteAllText(SaveFileDia.FileName, studentInfoHolder);
Also, you're right that File.WriteAllText overwrites the file content, so this line is useless:
File.WriteAllText(SaveFileDia.FileName, string.Empty);
Update
As #kevin correctly pointed out, it is more efficient to use StringBuilder in the loop instead of the string concatenation:
StringBuilder studentInfoHolder;
foreach (Stud student in StudentList)
{
studentInfoHolder.AppendFormat("Name: {0}\r\nSubject: {1}\r\nAge: {2}\r\nGrade: {3}",
student.Name, student.Subject, student.age, student.Grade);
}
File.WriteAllText(SaveFileDia.FileName, studentInfoHolder.ToString());
Try something more like the following. It avoids opening the file twice, and string concatenation, which is not a great idea with immutable strings.
// This line over-writes the file if it exists, or otherwise creates it.
using (TextWriter fileWriter = new StreamWriter(SaveFileDia.FileName, append: false))
{
foreach (Stud student in StudentList)
{
fileWriter.WriteLine($"Name: {student.Name}");
fileWriter.WriteLine($"Subject: {student.Subject}");
fileWriter.WriteLine($"Age: {student.age}");
fileWriter.WriteLine($"Grade: {student.Grade}");
fileWriter.WriteLine();
}
}
There's no good reason to buffer all that in memory before writing it to the file. It's easier to open the file by calling File.CreateText, and then write each line to it, like this:
private void saveTSMI_Click(object sender, EventArgs e)
{
if (lstStudNames.Items.Count == 0)
{
MessageBox.Show("Nothing to save");
return;
}
SaveFileDia.Filter = "Text Files | *.txt";
if (SaveFileDia.ShowDialog() != DialogResult.OK)
{
return;
}
// Create the file (overwrite if it already exists),
// and write each student record.
using (var outFile = File.CreateText(SaveFileDia.FileName))
{
foreach (Stud student in StudentList)
{
outFile.WriteLine("Name: " + student.Name);
outFile.WriteLine("Subject: " + student.Subject);
outFile.WriteLine("Age: " + student.age);
outFile.WriteLine("Grade: " + student.Grade);
}
}
}
I also refactored your code a bit, reversing the logic on those two tests up front so as to reduce the nesting in your code.
Update after comment
If you really want a string to contain all that stuff, then you can modify the above to do it pretty easily. Replace the loop that writes to file with this one that uses a StringWriter:
// Create a StringWriter to hold the data, and write each line.
using (var sWriter = new StringWriter())
{
foreach (Stud student in StudentList)
{
sWriter.WriteLine("Name: " + student.Name);
sWriter.WriteLine("Subject: " + student.Subject);
sWriter.WriteLine("Age: " + student.age);
sWriter.WriteLine("Grade: " + student.Grade);
}
// write the data to the file
StudentInfoHolder = sWriter.ToString();
File.WriteAllText(SaveFileDia.FileName, StudentInfoHolder);
}

how to copy multiple line from text file C#

I need to copy multiple lines from text file(cisco config file): based on the below condition
if the line starts with interface copy from interface until '! '
my file is like :
!
access-list 1>
!
interface 1
ip address xx.xx.xx.xx
!
interface 2
ip address xx.xx.xx.xx
!
route 1
!
I try the below code :
var lines = File.ReadAllLines("C:\\My File2.txt");
foreach (var line1 in lines){
string firstWord = line1.Split(' ').First();
if ((firstWord == "access-list") && (!line1.Contains("remark ")))
{
TextBox1.Text = TextBox1.Text + "\r\n" + line1;
}
else if (firstWord == "nat")
{
TextBox2.Text = TextBox2.Text + "\r\n" + line1;
}
else if (firstWord == "interface")
{
var result = lines.Substring(line1.LastIndexOf('!') + 1);
TextBox3.Text = TextBox3.Text + "\r\n" + result;
}
but I get only one line as output
In case you want to keep your algorithm, this will work for you.
var lines = File.ReadAllLines("C:\\My File2.txt");
int i;
for (i = 0; i<lines.Length;i++)
{
var line1 = lines[i];
if (line1 == "!" || line1 == " ") continue;
if (line1.StartsWith("access-list")) && (!line1.Contains("remark ")))
{
TextBox1.Text = TextBox1.Text + "\r\n" + line1;
}
else if (line1.StartsWith("nat"))
{
TextBox2.Text = TextBox2.Text + "\r\n" + line1;
}
if (line1.StartsWith("interface"))
{
var str = line1;
while (!Equals(lines[i + 1], "!"))
{
str += lines[i + 1];
i++;
}
TextBox3.Text = TextBox3.Text + "\r\n" + str;
}
}
As per the file structure shown by you interface and ip address are on different lines. So you won't get it in same iteration of for loop. When you find that firstWord == "interface" you will need to set a flag that will tell you that next line is ip address and in next iteration check if that flag is true parse the current line as ip address and process it the way you want.
You should use "File.ReadAllText" instead of "File.ReadAllLines". "File.ReadAllText" returns a string with the complete text file text. After that, you can use the "String.Split" method to generate a string array.
var lines = File.ReadAllText("C:\\My File2.txt");
var seperatedStrings = lines.Split('!');
Each index of "seperatedStrings" contains what you want.
UPDATE: Here is a code snippet, that can help:
var lines = File.ReadAllText("C:\\My File2.txt");
var seperatedStrings = lines.Split('!');
foreach (var oneString in seperatedStrings)
{
if (oneString.Contains("access-list"))
{
Console.WriteLine("Access-List: " + oneString);
}else if (oneString.Contains("nat"))
{
Console.WriteLine("Nat: " + oneString);
}else if (oneString.Contains("interface"))
{
Console.WriteLine("Interface: " + oneString);
}
}
This is the output of my code snippet:

Make string checker more efficient

I am using the following code to check if a string is contained within another string -
foreach (string testrecord in testlist)
{
foreach (string realrecord in reallist)
{
if ((Regex.Replace(testrecord , "[^0-9a-zA-Z]+", "")
.Contains((
Regex.Replace(realrecord, "[^0-9a-zA-Z]+", "")))
&&
((Regex.Replace(realrecord, "[^0-9a-zA-Z]+", "") != "")
&&
((Regex.Replace(realrecord, "[^0-9a-zA-Z]+", "").Length >= 4)))))
{
matchTextBox.AppendText("Match: " + testrecord + " & " + realrecord + Environment.NewLine);
}
}
}
However the runtime for this to finish is taking quite a while. Since I added the special character regex removal the runtime is taking a lot longer however the regex is definitely required.
Is there a more efficient way of applying this regex? I tried to add it to the foreach string variables however you cannot alter them as they are in a foreach loop.
Optimized version:
// Do not put text into matchTextBox direct:
// it makes the control re-painting each time you change the text
// Instead, collect all the text into StringBuffer
StringBuilder Sb = new StringBuilder();
// Pull out as much as you can from the inner loop,
// that's why I've changed the loops' order:
// first loop on reallist, then on testlist
foreach (string realrecord in reallist) {
// Cache Regex.Replace result
String realCleaned = Regex.Replace(realrecord, "[^0-9a-zA-Z]+", "");
// Test as early as possible
if (realCleaned.Length < 4)
continue;
// You don't need to test realCleaned != "";: realCleaned.Length < 4 is enough
foreach (string testrecord in testlist) {
// Cache Regex.Replace result: it's a little bit overshoot here, but if some
// more tests are added it'll be helpful
String testCleaned = Regex.Replace(testrecord, "[^0-9a-zA-Z]+", "");
if (testCleaned.Contains(realCleaned))
Sb.AppendLine("Match: " + testrecord + " & " + realrecord);
}
}
// At last matchTextBox.Text change
matchTextBox.AppendText(Sb.ToString());
This should be a bit quicker (one regex operation per testrecord):
var strippedRealList = reallist.Select(s => Regex.Replace(s, "[^0-9a-zA-Z]+", ""))
.Where(s => s.Length >= 4)
.ToArray();
foreach (string realrecord in reallist)
{
strippedRealList.Where(s => realrecord.Contains(s))
.ToList()
.ForEach(s =>
matchTextBox.AppendText("Match: "
+ s
+ " & "
+ realrecord
+ Environment.NewLine));
}
I wonder that you are using Regex to achieve your purpose ignoring the fact that you can also achieve this by only using .Contains() method such that your code should be simple and faster then before
foreach (string testrecord in testlist)
{
foreach (string realrecord in reallist)
{
if(testrecord.Contains(realrecord))
{
matchTextBox.AppendText("Match: " + testrecord + " & " + realrecord + Environment.NewLine);
}
}
}

String list remove

I have this code:
List<string> lineList = new List<string>();
foreach (var line in theFinalList)
{
if (line.PartDescription != "")
lineList.Add(line.PartDescription + " " + line.PartNumber + "\n");
else
lineList.Add("N/A " + line.PartNumber + "\n");
//
//This is what I am trying to fix:
if (lineList.Contains("FID") || lineList.Contains("EXCLUDE"))
// REMOVE THE item in the lineList
}
I am trying to go through theFinalList in a foreach loop and add each line to a new list called lineList.
Once added, I want to remove any entries from that list that contain the text "FID" or "EXCLUDE".
I am having trouble removing the entry, can someone help me?
why add them when you want to remove them right after:
lineList = theFinalList.Select( line =>
{
if (line.PartDescription != "")
return line.PartDescription + " " + line.PartNumber + "\n";
else
return "N/A " + line.PartNumber + "\n";
})
.Where(x => !(x.Contains("FID") || x.Contains("EXCLUDE")))
.ToList();
The following code sample iterates through the lineList and removes lines that contain FID or EXCLUDE.
for(int i = lineList.Count - 1; i >= 0; i--)
{
if (lineList[i].Contains("FID") || lineList[i].Contains("EXCLUDE"))
lineList.RemoveAt(i);
}
It is important to traverse a list in reverse order when deleting items.
You can't remove the items in your theFinalList list while you are iterating over theFinalList in a foreach loop. In this case, you may get System.InvalidOperationException with the message “Collection was modified; enumeration operation may not execute.”
you have to do something like this:
List<string> removals = new List<string>();
foreach (string s in theFinalList)
{
//do stuff with (s);
removals.Add(s);
}
foreach (string s in removals)
{
theFinalList.Remove(s);
}
try
foreach (var line in theFinalList)
{
string T = "";
if (line.PartDescription != "")
T = line.PartDescription + " " + line.PartNumber + "\n";
else
T = "N/A " + line.PartNumber + "\n";
if (!(T.Contains("FID") || T.Contains("EXCLUDE"))
lineList.Add (T);
}
I think its more logical approach
Regex exclude = new Regex("FID|EXCLUDE");
foreach (var line in theFinalList.Where(
ln => !exclude.Match(ln.PartDescription).Success &&
!exclude.Match(ln.PartNumber ).Success))){
string partDescription = "N/A";
if(!string.IsNullOrWhiteSpace(line.PartDescription)){
partDescription = line.PartDescription;
}
lineList.Add(partDescription + " " + line.PartNumber + "\n");
}
edit regex for your needs (ignore case maybe or multiline, probably compiled too) and feel free to replace "\n" with Environment.NewLine
Try this:
var excludingTexts = new [] { "FID", "EXCLUDE" }
lineList = lineList.Where(y => !excludingTexts.Any(x => line.PartDescription.Contains(x) || line.PartNumber.Contains(x))).ToList();
Or you can rewrite it as:
var excludingTexts = new [] { "FID", "EXCLUDE" }
List<string> lineList = (from line in theFinalList
where !excludingTexts.Any(x => line.PartDescription.Contains(x) || line.PartNumber.Contains(x))
select line.PartDescription != "" ?
line.PartDescription + " " + line.PartNumber + "\n" :
"N/A " + line.PartNumber + "\n"
).ToList();

Categories

Resources