How to display a string - c#

I am working on a small code that searches an input text file (of my choice). I am creating a search function. So far I got it to display how many times the search word occurs in the text file and also the line number. I need some help on displaying how the searched word appears in the text file. For example, If I search for the word "the" and it appears as "THE" or "The" in the text file, I would want to display that on my console window.
Any help, advice, or suggestion is appreciated. Thank you in advance!
Here is my code:
string line;
int counter = 0;
Console.WriteLine("Enter a word to search for: ");
string userText = Console.ReadLine();
string file = "NewTextFile.txt";
StreamReader myFile = new StreamReader(file);
int found = 0;
while ((line = myFile.ReadLine()) != null)
{
counter++;
if (line.Contains(userText))
{
Console.WriteLine("Found on line number: {0}", counter);
found++;
}
}
Console.WriteLine("A total of {0} occurences found", found);

You can use IndexOf instead of Contains since you want to do case-insensitive search:
if (line.IndexOf(userText, StringComparison.CurrentCultureIgnoreCase) != -1)
{
Console.WriteLine("Found on line number: {0}", counter);
found++;
}

This might do the trick for you
While ((line = myFile.ReadLine()) != null)
{
line = line.toUpper();
counter++;
if (line.Contains(userText.toUpper()))
{
Console.WriteLine("Found on line number: {0}", counter);
Console.WriteLine(line.SubString(line.IndexOf(userText),userText.Length));
found++;
}
}
Console.WriteLine("A total of {0} occurences found", found);
The line which is added here is
line.SubString(line.IndexOf(userText),userText.Length)
It means we need to find a SubString inside the line starting from the index of the first occurence of userText and the till the length of userText length
and if you wanted to only compare the string and show the original string you can use this code
While ((line = myFile.ReadLine()) != null)
{
string linecmp = line.toUpper();
counter++;
if (linecmp.Contains(userText.toUpper()))
{
Console.WriteLine("Found on line number: {0}", counter);
Console.WriteLine(line.SubString(line.IndexOf(userText),userText.Length));
found++;
}
}
Console.WriteLine("A total of {0} occurences found", found);

I have slightly modified your search function to resolve the issue you had before. As you mentioned in the comment, you said it is matching word 'THEIR' with word 'THE'.
Add the following code to resolve the mismatches issue.
string userText = Console.ReadLine() + " ";
Modified Full code below.
string line;
int counter = 0;
Console.WriteLine("Enter a word to search for: ");
string userText = Console.ReadLine() + " ";
string file = "NewTextFile.txt";
StreamReader myFile = new StreamReader(file);
int found = 0;
while((line = myFile.ReadLine()) != null)
{
line = line.ToUpper();
counter++;
if (line.Contains(userText.ToUpper()))
{
Console.WriteLine("Found on line number: {0}", counter);
Console.WriteLine(line.Substring(line.IndexOf(userText)+1,userText.Length));
found++;
}
}
Console.WriteLine("A total of {0} occurences found", found);
Console.ReadLine();
Hope this helps you.

Related

I'm trying to save array of strings to a txt file

I'm designing a program to save food recipes. The problem is when I save the ingredients of a new recipe it deletes the ingredients of the old recipe. I want both of them to be saved. Here's the code I use:
Console.WriteLine("Enter the path where your files will be saved: ");
string fileName = Console.ReadLine();
Console.WriteLine("Please enter the main ingrediant for your recipe: ");
string Main = Console.ReadLine();
Console.WriteLine("Please enter how many ingrediants in your recipe: ");
int Ingrediants = Convert.ToInt32(Console.ReadLine());
string[] a = new string[Ingrediants];
Recpies recipe1 = new Recpies(Main, Ingrediants);
recipe1.Ingrediants = new List<string[]>();
recipe1.TheMainIngrediant = Main;
Console.WriteLine("Please enter your ingrediants: ");
for (int i = 0; i < Ingrediants; i++)
{
a[i] = Console.ReadLine();
}
using (var file = System.IO.File.OpenText(fileName))
{
string line;
while ((line = file.ReadLine()?.Trim()) != null)
{
// skip empty lines
if (line == string.Empty)
{
recipe1.Ingrediants.Add(a);
recipe1.Saving(fileName, Ingrediants, a);
}
else
{
continue;
}
}
}
One possible way to achieve what you want is to use a combination between StreamWriter and File.AppendText, this is not going to overwrite the text you already save on that file instead of that is going to append the info at the end of the file (this example might be helpful: Append Text). Hope this helps! đź‘Ť
Just add true as second parameter
TextWriter tsw = new StreamWriter(fileName, true);

C# .txt file: Reading a substring in next line if previous line contains "X"

I am looking to read from a text file and if a line contains "XYZ" I need to return substrings within that line, then have the next line read for another substring.
There will be several lines that will return the "XYZ" and on each of these I will require the substring from the following line (Each of these will be a different value).
Currently I can return all instances of the substrings in the lines with "XYZ" but then either keep returning the same substring (which should be unique each time) from the line below the first "XYZ" or just, as below, each character individually.
So in the below snippet, from the log. If a line contains XYZ then I need to move to the next line and pull the Date/Time/and Batch Name Number.
XYZ will repeat several times through out the log, with different results each time.
2015-07-02 11:03:13,838 [1] INFO Place (null) (null) (null) – btnAction_Click, Completed Scan for _HAH_Claim_T, XYZ
2015-07-02 11:03:14,432 [1] INFO Place (null) (null) (null) – btnAction_Click, Set batch name 1234567
string[] lines = File.ReadAllLines(#"Text Document.txt");
foreach (string line in lines)
{
int success = line.IndexOf("XYZ");
if (success > 0)
{
string pass = "Pass";
string date = line.Substring(0, 10);
string time = line.Substring(11, 12);
int ID = line.LastIndexOf("XYZ");
if (ID != 0)
{
Console.WriteLine("\n\t" + pass + " Date: {0}\tTime: {1}", date, time);
}
string currentLine;
string batchID;
for (int i = 0; i < lines.Length; i++)
{
currentLine = lines.Skip(6).First();
batchID = currentLine.Substring(100);
Console.WriteLine("\tBatchID{0}", batchID[i]);
}
Console.WriteLine();
}
}
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
I do not completely understand the question as it is a bit abstract as to what you want to extract from each line but something like this will hopefully get you on the right track
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line.Contains("XYZ") && !reader.EndOfStream)
{
var nextLine = reader.ReadLine();
var pass = "Pass";
var date = nextLine.Substring(0, 10);
var time = nextLine.Substring(11, 12);
Console.WriteLine("\n\t" + pass + " Date: {0}\tTime: {1}", date, time);
}
}
}
the line variable is the one containing XYZ and next line is the line subsequent to that. If this is not meeting you requirements the please update the question to be a bit more specific
I would say something like this?
string[] lines = File.ReadAllLines(#"Text Document.txt");
for(int i = 0; i < lines.Length(); i++){
if(lines[i].Contains("XYZ")){
string pass = "Pass";
string date = line.Substring(0, 10);
string time = line.Substring(11, 12);
Console.WriteLine("\n\t" + pass + " Date: {0}\tTime: {1}", date, time);
// Retrieve the value in the next line
string nextLineAfterXYZ = lines[i + 1];
batchID = nextLineAfterXYZ.Substring(100);
Console.WriteLine("\tBatchID{0}", batchID);
}
}
You should add some error-handling, in case it's the last line (IndexOutOfBound) etc.
string[] lines = File.ReadAllLines(#"E:Sum.txt");
string str = string.Empty;
foreach (string line in lines)
{
if (line.Contains("x"))
{
str += line;
Console.WriteLine();
continue;
}
break;
}
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();

How can I edit numbers in my .txt file?

I have code here and based on user input, I'd like to change the line of choice I will have selected. However, I can only currently temporarily change the line of text and when I write out the file again, the text had not overwritten permanently.
Here's my code:
public struct classMates
{
public string first;
public string last;
public int ID;
}
static classMates[] readClassMates(classMates[] classMateInfo)
{
StreamReader sr = new StreamReader(#"C:\class.txt");
int count = 0;
while (!sr.EndOfStream)
{
classMateInfo[count].first = sr.ReadLine();
classMateInfo[count].last = sr.ReadLine();
string idTemp = sr.ReadLine();
classMateInfo[count].ID = Convert.ToInt32(idTemp);
count++;
}
sr.Close();
return classMateInfo;
}
static void editClassMates(classMates[] classMateInfo)
{
Console.Write("Who's number would you like to change? ");
string classMateInput = Console.ReadLine();
for (int i = 0; i < classMateInfo.Length; i++)
{
if (classMateInfo[i].first.Equals(classMateInput))
{
Console.Write("Enter new number: ");
string temp = Console.ReadLine();
int classMateNumber = Convert.ToInt32(temp);
classMateInfo[i].ID = classMateNumber;
Console.WriteLine("You have successfully changed {0}'s number to {1}.", classMateInfo[i].first,classMateInfo[i].ID.ToString());
}
}
}
static void Main()
{
classMates[] classMateInfo = new classMates[43];
listClassMates(classMateInfo);
editClassMates(classMateInfo);
listClassMates(classMateInfo);
}
I know I am meant to use File.WriteAllText(), but I don't know how to utilize this snippet into my code.
Maybe you're expecting an easy answer but you actually require custom code that you need to think up yourself.
If you're into LINQ and really want to use the File.WriteAllText() method you can use this oneliner i wrote for you, which I haven't tested:
File.WriteAllText(#"C:\class.txt", string.Join(Environment.NewLine, (from cm in classMateInfo select string.Format("{1}{0}{2}{0}{3}", Environment.NewLine, cm.first, cm.last, cm.ID)).ToArray()));
Which creates a string array from your classMateInfo, concatenates the array using a newline as separator and write the entire string to the specified file.
I don´t see you writing anything to a file.
Console.Write("Enter new number: ");
string temp = Console.ReadLine();
int classMateNumber = Convert.ToInt32(temp);
classMateInfo[i].ID = classMateNumber;
Console.WriteLine("You have successfully changed {0}'s number to {1}.", classMateInfo[i].first,classMateInfo[i].ID.ToString());
I should expect that you did something like:
rs.Writeline('foo');
But perhaps you need a streamwriter for that.

Ignoring white space in palindrome

I am writing a program to check if a word is palindrome. The program itself works
but when I enter this specific line of text "too bad - i hid a boot" it will not pick it up
and ignore the white space and hyphen.
I looked at previous questions but I cant find a answer.
Is my Regex.Replace incorrect?
string s, revs = "";
Console.WriteLine("Please Enter Word");
s = Console.ReadLine();
string r = Regex.Replace(s , #"[^-\s]", "");
for (int i = s.Length-1; i >= 0; i--)
{
revs += s[i].ToString();
}
if (revs == s)
{
Console.WriteLine("Entered string is palindrome \n String was {0} and reverse string was {1}", s, revs);
}
else
{
Console.WriteLine("String entered was not palindrome.");
}
Console.ReadKey();
Your code contains two errors:
This is the correct Regex condition #"(\s|-)" yours replaces everything but the characters you want to remove
As jeffdot pointed out, you're replacing (incorrectly) but then testing against the original string
This considered, the correct code should be:
string s, revs = "";
Console.WriteLine("Please Enter Word");
s = Console.ReadLine();
string r = Regex.Replace(s , #"(\s|-)", "");
for (int i = r.Length-1; i >= 0; i--)
{
revs += r[i].ToString();
}
if (revs == r)
{
Console.WriteLine("Entered string is palindrome \n String was {0} and reverse string was {1}", s, revs);
}
else
{
Console.WriteLine("String entered was not palindrome.");
}
Console.ReadKey();
Except for the first WriteLine in which you should decide what to print (since revs doesn't contain spaces and the hyphen anymore).
Or if you want to just use String.Replace, you can use it twice with:
s=s.Replace(' ','');
s=s.Replace('-','');
You are assigning the result of that Regex.Replace call to string r and you are never referencing it. This is why your comparison is failing.
To make that more clear: you are removing whitespace and referencing that product as string r but you are reversing and testing against string s only.
Saverio also points out that your regex isn't going to work (I didn't test that myself).
You have:
string r = Regex.Replace(s , #"[^-\s]", "");
for (int i = s.Length-1; i >= 0; i--)
{
revs += s[i].ToString();
}
Right there you should be iterating and reversing r instead of s --because s still has all its whitespace.
Further, as Saverio has said, why not just replace?
string r = s.Replace(" ", string.Empty).Reverse();
I haven't tried to compile that but as long as you are not using a very old version of the .NET framework that should work. It may require that you are using System.Linq to use the Reverse() extension.

How can I add a new line to a text document

I was wondering, how can i add a new line to a text document. For an instance, I have a text document with numbers or whatever which contains the following two lines of text:
"444444
323233"
And I want to add a new line, in which would like to add new combination of numbers, so how can I do that? I first save all lines in a array, print them and ask the user to choose which line to edit and if the chosen line does not exist (in this situation if the user types the number "3" in the variable n), I want the program to create a new line.
string path = C:\...\text1.text
string[] lines = File.ReadAllLines(path);
int i = 1;
foreach (var line in lines)
{
Console.WriteLine("{0}. {1}", i, line);
i++;
}
Console.Write("Choose which line to edit: ");
int n = int.Parse(Console.ReadLine());
n--;
Console.Write("{0}. ", n + 1);
lines[n] = lines[n].Replace(lines[n], Console.ReadLine());
File.WriteAllLines(path, lines);
Thanks!
Replace following line of code with mention code:
string path = C:\...\text1.text
List<string> lines = File.ReadAllLines(path);
int i = 1;
foreach (var line in lines)
{
Console.WriteLine("{0}. {1}", i, line);
i++;
}
Console.Write("Choose which line to edit: ");
int n = int.Parse(Console.ReadLine());
n--;
Console.Write("{0}. ", n + 1);
lines.Insert(n, Console.ReadLine());
File.WriteAllLines(path, lines.ToArray());
Environment.NewLine Property Gets the newline string defined for this environment.
// Sample for the Environment.NewLine property
using System;
class Sample
{
public static void Main()
{
Console.WriteLine();
Console.WriteLine("NewLine: {0} first line{0} second line{0} third line",
Environment.NewLine);
}
}
/*
This example produces the following results:
NewLine:
first line
second line
third line
*/
Take a look here:
AppendAllText
For all File Methods:
File Methods
The AppendAllText has a signature:
public static void AppendAllText(
string path,
string contents
)
to use:
File.AppendAllText("path/to/file/that/exists/myfile.txt", "Your new line here");

Categories