How to read character in a file 1 by 1 c# - c#

I want my program to read a text file all characters 1 by 1 and whereever it finds a double-quote ("), it adds a semicolon before that inverted comma. For eg we have a paragraph in a text file as follow:
This is a paragraph which conains lots and lots of characters and some
names and dates. My name "Sam" i was born at "12:00" "noon". I live in
"anyplace" .
Now I want the output to be as follows:
This is a paragraph which conains lots and lots of characters and some
names and dates. My name ;"Sam;" i was born at ;"12:00;" ;"noon;". I
live in ;"anyplace;" .
It should open the file using file stream then reads character and then adds semicolon where it finds quotes. And the output should be equal to textbox1.Text.
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
char ch;
int Tchar = 0;
StreamReader reader;
reader = new StreamReader(#"C:\Users\user1\Documents\data.txt");
do
{
ch = (char)reader.Read();
Console.Write(ch);
if (Convert.ToInt32(ch) == 34)
{
Console.Write(#";");
}
Tchar++;
} while (!reader.EndOfStream);
reader.Close();
reader.Dispose();
Console.WriteLine(" ");
Console.WriteLine(Tchar.ToString() + " characters");
Console.ReadLine();
}
}
}
This is the output:
This is a paragraph which conains lots and lots of characters and some
names and dates. My name ";Sam"; i was born at ";12:00"; ";noon";. I
live in ";anyplace"; . 154 characters
I want that semicolon before the quotes. Any help would be appreciated. Thanks!

Swap the order of the operations:
if (Convert.ToInt32(ch) == 34)
{
Console.Write(#";");
}
Console.Write(ch);
e.g. don't write the original character until AFTER you've decided to output a semicolon or not.

Try ch = (char)reader.Peek();
This will read tell you the next character without reading it. You can then use this to check if it is a " or not an insert : accordingly
if (Convert.ToInt32((char)read.Peek()) == 34) Console.Write(#";")

Do you have to read in character by character? The following code will do the whole thing as a block and return you a list containing all your lines.
var contents = File.ReadAllLines (#"C:\Users\user1\Documents\data.txt")
.Select (l => l.Replace ("\"", ";\""));

using System;
using System.IO;
using System.Text;
namespace getto
{
class Program
{
static void Main(string[] args)
{
var path = #"C:\Users\VASANTH14122018\Desktop\file.v";
string content = File.ReadAllText(path, Encoding.UTF8);
Console.WriteLine(content);
//string helloWorld = "Hello, world!";
foreach(char c in content)
{
Console.WriteLine(c);
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}

Related

How to insert a string every n words?

I need help with text. I got a code which for example finds if the line has even number of words, then it finds every 2nd word in a text file. The problem is i don't know how to append a string to that every 2nd word and print it out.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.IO;
namespace sd
{
class Program
{
const string CFd = "..\\..\\A.txt";
const string CFr = "..\\..\\Rezults.txt";
static void Main(string[] args)
{
Apdoroti(CFd, CFr);
Console.WriteLine();
}
static void Apdoroti(string fd, string fr)
{
string[] lines = File.ReadAllLines(fd, Encoding.GetEncoding(1257));
using (var far = File.CreateText(fr))
{
StringBuilder news = new StringBuilder();
VD(CFd,news);
far.WriteLine(news);
}
}
static void VD(string fv, StringBuilder news)
{
using (StreamReader reader = new StreamReader(fv,
Encoding.GetEncoding(1257)))
{
string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));
int nrl;
int prad = 1;
foreach (string line in lines)
{
nrl = line.Trim().Split(' ').Count();
string[] parts = line.Split(' ');
if (nrl % 2 == 0)
{
Console.WriteLine(nrl);
for (int i = 0; i < nrl; i += 2)
{
int ind = line.IndexOf(parts[i]);
nauja.Append(parts[i]);
Console.WriteLine(" {0} ", news);
}
}
}
}
}
}
}
For example if i got a text like:
"Monster in the Jungle Once upon a time a wise lion lived in jungle.
He was always respected for his intelligence and kindness."
Then it should print out:
"Monster in abb the Jungle abb Once upon abb a time abb a wise abb lion lived abb in jungle.
He was always respected for his intelligence and kindness."
You can do it with a regex replace, like this regex:
#"\w+\s\w+\s"
It maches a Word, a Space, a Word and a Space.
Now replace it with:
"$&abb "
How to use:
using System.Text.RegularExpressions;
string text = "Monster in the Jungle Once upon a time a wise lion lived in jungle. He was always respected for his intelligence and kindness.";
Regex regex = new Regex(#"\w+\s\w+\s");
string output = regex.Replace(text, "$&abb ");
Now you will get the desired output.
Edit:
To Work with any number of Words, you can use:
#"(\w+\s){3}"
where the quantifier (here 3) can be set to whatever you want.
Edit2:
If you don't want to replace numbers:
#"([a-zA-Z]+\s){2}"
You can use linq, first parse the line on spaces to get a list of words (you are doing) and then for every odd element add the text required, finally convert the array back into a string.
string test = "Monster in the Jungle Once upon a time a wise lion lived in jungle. He was always respected for his intelligence and kindness.";
var words = test.Split(' ');
var wordArray = words.Select((w, i) =>
(i % 2 != 0) ? (w+ " asd ") : (w + " ")
).ToArray();
var res = string.Join("", wordArray);
Also this can be easily changed to insert after every n words by changing the mod function. Do remember that array index will start at 0 though.

Difficulty answering self study homework using a dictionary

Hello there again dear friends. I do not for the word of me understand what is going on in this code. I'm trying to implement a dictionary that counts the instances that a word pops up disregarding upper case or not. It keeps showing "isthis" and I dont know where its coming from. How do i rectify this?
The question is as such
Write a program that counts how many times each word from a given
text file words.txt appears in it. The result words should be ordered by
their number of occurrences in the text.
Here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
namespace Chapter_18_Question_3
{
class Program
{
static void Main(string[] args)
{
const string path = "words.txt";
string line;
using (var reader = new StreamReader(path))
{
line = reader.ReadToEnd();
}
string text = line.ToLower();
string tmp = Regex.Replace(text, "[^a-zA-Z0-9 ]", "");
string[] newText = tmp.Split(' ');
var table = new SortedDictionary<string, int>();
foreach(var item in newText)
{
if(!table.ContainsKey(item))
{
table.Add(item, 1);
}
else
{
table[item] += 1;
}
}
foreach (var item in table)
{
Console.WriteLine("The word {0} appeared {1} times",
item.Key, item.Value);
}
}
}
My text is this:
"This is the TEXT. Text, text, text – THIS TEXT! Is this the text?"
And the output is this
The word appeared 1 times
The word is appeared 1 times
The word isthis appeared 1 times
The word text appeared 6 times
The word the appeared 2 times
The word this appeared 2 times
If I were to guess, I'd say that your file contains a line break (LF or CRLF) that gets replaced by your regex (which only allows letters and spaces).
For instance, if the file contents were:
This
is the text.
The line break between This and is would be removed, leaving you with the text:
Thisis the text.
If this is the case, you might want to use "[^a-zA-Z0-9 \r\n]" instead as a replacement pattern.

How to Turn a Randomized String Array 'word' into an array made up of the string's Characters C#?

Okay, so I'm creating a hang-man game (Lame, I know, but I gotta' start somewhere). I have successfully pulled ~30 random words from a text file into a variable and can properly display the word in a random order onto the screen (just to test and make sure the variable is obtaining a whole word in random order).
But I need to take that string and break it into single characters in order to 'blank' out the letters to be 'guessed' by the user. I assume an array is the best way to do this - coupled with a while loop that will run while the character != null.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hangman
{
class Program
{
static void Main(string[] args)
{
String[] myWordArrays = File.ReadAllLines("WordList.txt");
Random randomWord = new Random();
int lineCount = File.ReadLines("WordList.txt").Count();
int activeWord = randomWord.Next(0, lineCount);
/*CharEnumerator activeWordChar = activeWord; --- I have tried this,
but it says "Cannot implicitly convert type 'int' to 'System.CharEnumerator'
--- while redlining "activeWord." */
/*CharEnumerator activeWordChar = activeWord.ToString
-- I have tried this but it says "Cannot convert method group 'ToString' to
non-delegate type 'System.CharEnumerator'. Did you intend to invoke the method?
I also tried moving the declaration of activeWordChar below the 'writeline'
that displays the word properly to the console.
I have even tried to create a Char[] activeWordChar = activeWord.toCharArray; But this doesn't work either.
*/
//I'm using this writeline "the word for this game is: " ONLY to test that the
//system is choosing random word **end comment
Console.WriteLine("The Word for this game is: " + myWordArrays[activeWord]);
//Console.WriteLine("The Characters are like this: " + activeWordChar[]);
//my attempt at printing something, but it doesn't work. :(
Console.ReadLine();
}
}
}
I'm open to references in order to figure it out myself, but I'm kinda' stuck here.
Also, how do I close the file that I've opened so that it can be accessed later on in the program if need be? I've only learned the StreamReader("filename") way of 'variable.Close();' - but that isn't working here.
Edit
And why someone would vote this question down is beyond me. lol
A couple of points here (first of all, you are off to a great start):
You are needlessly re-reading your file to get the line count. You can use myWordArrays.Length to set your lineCount variable
Regarding your question about closing the file, per MSDN File.ReadAllLines() closes the file after it is done reading it, so you are fine there with what you already have.
A string itself can be treated like an array in terms of accessing by index and accessing its Length property. There's also the ability to iterate over it implicitly like so:
foreach (char letter in myWordArrays[activeWord])
{
// provide a blanked-out letter for each char
}
You can access any character in the string by its index, so you can think of string as array of chars:
For example, like this snippet:
string word = "word";
char w1 = word[0];
Console.WriteLine(w1);
You can simplify your code a bit as follows. Previously your activeWord variable was an integer and therefore cannot be converted to a character array.
static void Main(string[] args)
{
String[] myWordArrays = File.ReadAllLines("WordList.txt");
Random random = new Random();
string activeWord = myWordArrays[random.next(myWordArrays.Length)];
char[] chars = activeWord.ToCharArray();
}
However a string in C# can be treated as an enumerable object and therefore you should only be using a character array if you need to mutate parts of the string.
Thanks to Sven, I was able to figure it out and I was able to add some things onto it as well!! I'm posting this for other newbs to understand from a newb's perspective:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hangman
{
class Program
{
static void Main(string[] args)
{
printWord();
}
/*I created a method to perform this, so that I can have the program stay open for
either 1) a new game or 2) just to see if I could do it. It works!*/
private static void printWord()
{
String[] myWordArrays = File.ReadAllLines("WordList.txt");
Random randomWord = new Random();
//int lineCount = File.ReadLines("WordList.txt").Count();
//The line below fixed my previous issue of double-reading file
int activeWord = randomWord.Next(0, myWordArrays.Length);
string userSelection = "";
Console.WriteLine("Are you Ready to play Hangman? yes/no: ");
userSelection = Console.ReadLine();
if(userSelection == "yes")
{
/*This runs through the randomly chosen word and prints an underscore in
place of each letter - it does work and this is what fixed my
previous issue - thank you Sven*/
foreach(char letter in myWordArrays[activeWord])
{
Console.Write("_ ");
}
//This prints to the console "Can you guess what this 'varyingLength' letter word is?" - it does work.
Console.WriteLine("Can you guess what this "+ myWordArrays[activeWord].Length +" letter word is?");
Console.ReadLine();
}
//else if(userSelection=="no") -- will add more later
}
}
}

What is the Most Efficient way to Place Strings to Array from .txt

I have a text file with about 30 words (of varying length). I'm trying to bring all of those words into the program and store them into an array of 'x' elements (x being the number of words).
Any help? I'm literally on day 2 of learning.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hangman {
class Program {
static void Main(string[] args) {
//StreamReader myWordList = new StreamReader("WordList.txt");//string stringArray[] = StreamReader(WordList.txt);//.WordList.txt;
String myWordArrays[] = File.ReadAllLines(#
"C:\Users\YouTube Upload\Documents\Visual Studio 2013\Projects\Hangman");
Console.WriteLine(myWordArrays[2]);
Console.ReadLine();
}
}
}
This is the complete code (above) - I'm getting these errors:
Error 1 Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. c:\users\youtube upload\documents\visual studio 2013\Projects\Hangman\Hangman\Program.cs 16 32 Hangman
And
Error 2 Invalid expression term '=' c:\users\youtube upload\documents\visual studio 2013\Projects\Hangman\Hangman\Program.cs 16 35 Hangman
I don't really understand that, because I'm calling it like I should be (or so I would think? o.0)
And this:
Error 3 ; expected c:\users\youtube upload\documents\visual studio 2013\Projects\Hangman\Hangman\Program.cs 16 35 Hangman
also this one
Error 4 ; expected c:\users\youtube upload\documents\visual studio 2013\Projects\Hangman\Hangman\Program.cs 16 37 Hangman
Forgive my horrible formatting here - I'm new to this site and am just getting used to it all. :(
Get values from file like this :
string[] myWordArrays = File.ReadAllLines(#"C:\Users\YouTube Upload\Documents\Visual Studio 2013\Projects\Hangman\yourfilename");
Your whole program :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hangman {
class Program {
static void Main(string[] args) {
string[] myWordArrays = File.ReadAllLines(#"C:\Users\YouTube Upload\Documents\Visual Studio 2013\Projects\Hangman\yourfilename");
Console.WriteLine(myWordArrays[2]);
Console.ReadKey();
}
}
}
P.S. What mistakes have you made in this line of code
String myWordArrays[] = File.ReadAllLines(#
"C:\Users\YouTube Upload\Documents\Visual Studio 2013\Projects\Hangman\");
Incorrect variable declaration. Correct one is
string[] myWordArrays = ...
'#' sign should be placed right before string that contain escape characters and should be on a same line. What if line is too long? Then you can move both this sign and the string to a next line.
string[] myWordArrays = File.ReadAllLines(
#"C:\Users\YouTube Upload\Documents\Visual Studio 2013\Projects\Hangman");
File.ReadAllLines method accepts only full path and not a relative one. To point to a file that is located in the same folder where executive file is stored (bin folder) you can use Directory.GetCurrentDirectory() method. So you can change it to :
string filename = 1.txt;
File.ReadAllLines(Directory.GetCurrentDirectory() + "\" + filename);
Depending on the character(s) used to split the strings, you could use one of the following:
var streamReader = new StreamReader("file");
var words = streamReader.ReadToEnd();
var wordArray = words.Split(new[] { Environment.NewLine }, StringSplitOptions.None); // For words split by lines where you know the format of the line ending
var wordArray = words.Split(new [] {"\n", "\r\n"}, StringSplitOptions.None); // For words split by lines where the format could be unix or windows
var wordArray = words.Split(','); // For words split by comma
So, for more explination StreamReader.ReadToEnd() returns a string. This class has many methods as defined in:
https://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx
These methods include a "split" method, which takes either an array of characters (or multiple comma separated characters) (char denoted by single quote (')) or an array of strings with string split options.
In the latter, we define a new array of strings with new [] { "string1", "string2", "..."} here the type of the array is implicit, but we could specify new string[] {...} if we wanted, or pass in an array of strings we had already defined. The second option is an enum with two values; None and RemoveEmptyEntries, which are defined here:
https://msdn.microsoft.com/en-us/library/system.stringsplitoptions(v=vs.110).aspx
There are additional overloads for the string.split method (which are in the top link).
I would like to thank all of you for the tremendous help. I had the formatting incorrect, but I guess I understood how it worked after all!! lol. At least it wasn't a misplaced/missing semicolon, yeah? :)
namespace Hangman
{
class Program
{
static void Main(string[] args)
{
//StreamReader myWordList = new StreamReader("WordList.txt");//string stringArray[] = StreamReader(WordList.txt);//.WordList.txt;
String[] myWordArrays = File.ReadAllLines("WordList.txt");
Console.WriteLine(myWordArrays[2]);
Console.ReadLine();
}
}
}
Thank you all so very much. This fixed it, and it did successfully display the 3rd element (string), which is advice, which happens to be on the third line [2] - perfect. Thank you!!!
Try this, it may help you.
private void PutTextIntoArray()
{
var array = ReadTextFile("C:\\WordList.txt").GetTotalWords();
}
private static string ReadTextFile(string file)
{
try
{
return File.ReadAllText(file);
}
catch (IOException ex)
{
return ex.Message;
}
catch (Exception ex)
{
return ex.Message;
}
}
public static class Extensions
{
public static string ReplaceMultipleSpacesWith(this string text, string newString)
{
return Regex.Replace(text, #"\s+", newString);
}
public static string[] GetTotalWords(this string text)
{
text = text.Trim().ReplaceMultipleSpacesWith(" ");
var words = text.Split(' ');
return words;
}
}

reversing text from input file using linq

I would like to reverse each word from input.txt using c# and linq and display the output text, so far i have a code that inputs the word and reverses it.
using System;
using System.Text;
using System.Linq;
namespace program
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("String:");
string name = Console.ReadLine();
string output = new string(name.ToCharArray().Reverse().ToArray());
Console.WriteLine(output);
}
}
}
string input = "I love programming";
string output = String.Join(" ",
input.Split().Select(w => new String(w.Reverse().ToArray())));
// I evol gnimmargorp
Reading file is simple:
string input = File.ReadAllText("input.txt");
You can also move word reversing into separate method. That will allow you to change algorithm of string reversing without touching other logic:
private static string GetReversedString(string s)
{
return new String(s.Reverse().ToArray());
}
And getting reversed output will look like:
string output = String.Join(" ", input.Split().Select(GetReversedString));
If lines should be preserved:
string output =
String.Join(Environment.NewLine,
File.ReadLines().Select(l =>
String.Join(" ", l.Split().Select(GetReversedString))));
The reversal code could be refactored in an extension method for String; Next, a text file should be opened, the lines splitted to single words and the words mapped reversely to the console.

Categories