Reading individual words into an array using streamreader C# - c#

I am trying to get a list of words (below) to be put into an array. I want each word to be in it's own index.
Here is my code that I have so far.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWordsLine = line.Split(' ');
int BadWordArrayCount = 0;
foreach (string word in badWordsLine)
{
badWords[BadWordArrayCount] = word;
BadWordArrayCount = BadWordArrayCount + 1;
}
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
Here is the list of words I want to import.
label
invoice
post
document
postal
calculations
copy
fedex
statement
financial
dhl
usps
8
notification
n
irs
ups
no
delivery
ticket
If someone could give me an example of how to get this to work, that would be a huge help.

Simplified code:
string badWordsFilePath = openFileDialog2.FileName.ToString();
string[] badWords = File.ReadAllLines(badWordsFilePath);
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;

If every word starts on a new line then you do not need to create a for loop. The Split method will convert to an array for you.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWords = line.Split('\n');

You are splitting on space, but there is a newline between each word. Split on newline instead:
string[] badWordsLine = line.Split(new string[]{ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
Then you have to create the array to put the words in:
badWords = new string[badWordsLine.Length];
However, to loop through a string array just to copy the strings to a string array seems pointless. Just assing the string array to the variable. Also, you forgot to close the stream reader, which is best taken care of with a using block:
string badWordsFilePath = openFileDialog2.FileName.ToString();
string line;
using (StreamReader sr = new StreamReader(badWordsFilePath)) {}
line = sr.ReadToEnd();
}
badWords = line.Split(new string[]{ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;

Maybe try this modification? It allows on splitting on various white spaces.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWordsLine = line.Split(new string[] {" ", "\t", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
int BadWordArrayCount = 0;
foreach (string word in badWordsLine)
{
badWords[BadWordArrayCount] = word;
BadWordArrayCount = BadWordArrayCount + 1;
}
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;

Do you have to use a StreamReader? If you do not have to, then this code is clearer (in my opinion).
string text = File.ReadAllText(badWordsFilePath);
string[] words = Regex.Split(text, #"\s+");
If you're 100% certain that each word is on its own line and there are no empty lines, this might be overkill; and the File.ReadAllLines suggestion by #Ulugbek Umirov is simpler.

Related

Split string and keep delimiter in sequence [duplicate]

This question already exists:
C# split string but keep split chars / separators [duplicate]
Closed 4 years ago.
Is there a clever way to do the following string manipulation in C#?
I have any kind of string and im looking for a specified delimiter. The code should divide the string in words before and after delimiter and also include the delimiter. The delimiter could be several times in a row and also could be in the start or the end.
// PSEUDO CODE
string = "Hello****wide****world";
delimiter = "****";
// result should be a list<string> like
{"Hello","****","wide","****","world"}
You can try to use Regex and the pattern is (\*{4}).
string data = "Hello****wide****world";
string[] words = Regex.Split(data, #"(\*{4})");
List<string> result = words.ToList();
NOTE
* is a keyword in regex string, so you need to use \ to escape it.
c# online
i'll say split the string with the delimiter, then when creating the result add the delimiter after each item in the array.
string fullWord = "Hello****wide****world";
string delimiter = "****";
var listOfWords = fullWord.Split(delimiter);
List<string> result = new List<string>();
foreach(var item in listOfWords){
result.Add(item);
result.Add(delimiter);
}
return result;
You can do it like this. In the end, you can iterate over the result.
string input = "Hello****wide****world";
string delimiter = "****";
var listOfWords = input.Split(new string[] { delimiter }, StringSplitOptions.None);
List<string> result = new List<string>();
foreach (var item in listOfWords)
{
if (!item.Equals(listOfWords.Last()))
{
result.Add(item);
result.Add(delimiter);
}
else
{
result.Add(item);
}
}
untested
string[] words = Regex.Split(originalString, #"(?=****)");
List<string> wordsLst = words.ToList();
User Regex to do it :
string input = "Hello****wide****world";
string pattern = "(****)";
string[] substrings = Regex.Split(input, pattern);
string fullWord = "Hello****wide****world";
string delimiter = "****";
var listOfWords = fullWord.Split(delimiter);
StringBuilder result = new StringBuilder("");
result.Append("{");
foreach(var item in listOfWords){
if (!item.Equals(listOfWords.Last()))
{
result.Append($"\"{item}\",\"{delimiter}\",");
}
else
{
result.Append($"\"{item}\"");
}
}
result.Append("}");
var stringResult=result.ToString();

How to split by multiple strings in C#

My Question consists of how might i split a string like this:
""List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2
\tdevice\r\n\r\n"
Into:
[n9887bc314,n12n1n2nj1jn2]
I have tried this but it throws the error "Argument 1: cannot convert from 'string' to 'char'"
string[] delimiterChars = new string[] {"\\","r","n","tdevice"};
string y = output.Substring(z+1);
string[] words;
words = y.Split(delimiterChars, StringSplitOptions.None);
I'm wondering if i'm doing something wrong because i'm quite new at c#.
Thanks A Lot
First of all String.Split accept strings[] as delimiters
Here is my code, hope it will helps:
string input = "List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] delimiterChars = {
"\r\n",
"\tdevice",
"List of devices attached"
};
var words = input.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
{
Console.WriteLine(word);
}
Split the whole string by the word device and then remove the tabs and new lines from them. Here is how:
var wholeString = "List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
var splits = wholeString.Split(new[] { "device" }, StringSplitOptions.RemoveEmptyEntries);
var device1 = splits[1].Substring(splits[1].IndexOf("\n") + 1).Replace("\t", "");
var device2 = splits[2].Substring(splits[2].IndexOf("\n") + 1).Replace("\t", "");
I've been doing a first aproach and it works, it might help:
I splited the input looking for "/tdevice" and then cleaned everyting before /r/n including the /r/n itself. It did the job and should work with your adb output.
EDIT:
I've refactored my answer to consider #LANimal answer (split using all delimiters) and I tried this code and works. (note the # usage)
static void Main(string[] args)
{
var inputString = #"List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] delimiters = {
#"\r\n",
#"\tdevice",
#"List of devices attached"
};
var chunks = inputString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string result = "[";
for (int i = 0; i < chunks.Length; i++)
{
result += chunks[i] + ",";
}
result = result.Remove(result.Length - 1);
result += "]";
Console.WriteLine(result);
Console.ReadLine();
}
I hope it helps,
Juan
You could do:
string str = #"List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] lines = str.Split(new[] { #"\r\n" }, StringSplitOptions.None);
string firstDevice = lines[1].Replace(#"\tdevice", "");
string secondDevice = lines[2].Replace(#"\tdevice", "");

Read text file and split it over

So, I know my headline is a bit confusing, I will explain.
My code looks like this:
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamReader sr = new StreamReader(filename);
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
while ((map = sr.ReadLine()) != null)
{
maps.Add(map);
}
sr.Close();
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
and what i need to do is when the code read a new line, in my line there is
"Hey,Hey"
I want to split the , from each other so I can take both of them as other parameters, so that the first Hey will be added to maps and the other hey will be maps2,
How can I do that?
You can use Split() function to Split the given String based on delimiter.
Try This:
while ((map = sr.ReadLine()) != null)
{
maps.Add(map.Split(',')[0].Trim());
maps2.Add(map.Split(',')[1].Trim());
}
Simple Code:
using System.IO;
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
List<string> maps2 = new List<string> { };
String [] allLines = File.ReadAllLines(filename);
foreach(String line in allLines)
{
maps.Add(line.Split(',')[0].Trim());
maps2.Add(line.Split(',')[1].Trim());
}
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
Solution 2:
String mapItem1="";
String mapItem2="";
if(maps.Count == maps2.Count)
{
for(int i=0;i<maps.Count;i++)
{
mapItem1=maps[i];
mapItem2=maps2[i];
}
}
while ((map = sr.ReadLine()) != null)
{
string[] split = map.Split(',');
//First Hey would be split[0], second Hey would be split[1]
maps.Add(split[0].Trim());
maps2.Add(split[1].Trim());
}
The Split method should help you out with that.
If you want to trim leading whitespace characters, you can use the .Trim() method on a string.
Use Split().
string heys = "Hey,Hey";
string[] splitArray = heys.Split(',');
Then you have:
splitArray[0] = "Hey";
splitArray[1] = "Hey";
Why even bother reading line by line? Read the entire file, replace the new line chars for a "," (to prevent last and first elements from different lines to be treated as one), and loop through a clean string.
string fileContent = Regex.Replace(File.ReadAllText("test.txt"), #"\r", ",");
List<string> mapList = new List<string>();
foreach (string map in Regex.Split(fileContent.Replace(#"\s+", ""), ","))
{
mapList.Add(map.Trim());
}

Reading text files one word at a time until end of file and display on textblock

I am looking for a way I can read a text file, one word at a time, until the end of the file.
This is my code at the moment but it is only reading one word from the file and no more.
How can I process the entire file?
var ResourceStream = Application.GetResourceStream(new Uri("test.txt",UriKind.Relative));
using (Stream myFileStream = ResourceStream.Stream)
{
string s = "";
StreamReader myStreamReader = new StreamReader(myFileStream);
s = myStreamReader.ReadToEnd();
s = s.Trim();
//tlbwords.Text = s;
char[] delimiters = { '\n', '\r' };
string[] words = s.Split(delimiters);
tlbwords.Text = words[0];
}
}
}
}
You can use String[] lines = File.ReadAllLines(fileName); and then separate the words.
Using LINQ to get all words:
var words = File
.ReadAllLines(fileName)
.SelectMany(line -> line.Split(' '))
.Where(word => !string.IsNullOrWhiteSpace())
.ToArray();
Edit with Julián Urbano suggestion:
var words = File
.ReadAllLines(fileName)
.SelectMany(line -> line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.ToArray();
Why not use:
textbox1.Text = File.ReadAllText(filename);
and set Multiline to true

Exception "String cannot be of Zero length"

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.

Categories

Resources