I know this is probably a newbie question but I need help with my first C# program.
I need to extract some strings from a file. Every line looks like this:
630 FWTRGS782BT a-p 66.12.111.198
and need to only retrieve (it is a serial number):
FWTRGS782BT
I was thinking the correct way could to use line.Substring() but I really don't know how to retrieve it.
Actually every serial number starts by FG or FW, so it could may be possible to extract whenever I get a match with those first two letters and get up till the end of the string (or /t)?
Try this:
string line = "630 FWTRGS782BT a-p 66.12.111.198";
var lineArr = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var requiredText = lineArr.Where(x => !string.IsNullOrEmpty(x) && x.StartsWith("FW") || x.StartsWith("FG"));
Here an example of how to read all serial numbers from a file
private List<string> GetAllSerialNumbersFromDocument(string pathToFile) //something like "C://folder/folder/file.txt"
{
List<string> serialNumbers = new List<string>(); //list where all serial numbers are stored
using (System.IO.StreamReader file = new StreamReader(pathToFile)) //Use 'using' because TextReader implements IDisposable
{
string line;
while ((line = file.ReadLine()) != null) //read all lines
{
serialNumbers.Add(GetSerialNumber(line)); //Get serial number of line and save it into list
}
}
return serialNumbers; //return all serial numbers
}
private string GetSerialNumber(string line)
{
var singleElements = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries); //split elements
return singleElements.First(x => x.StartsWith("FW") || x.StartsWith("FG")); //Get serial number
}
var input = "630 FWTRGS782BT a-p 66.12.111.198";
var output = input.Split( new char []{ ' ' },
StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(output[1]); //➙ FWTRGS782BT
Related
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", "");
I need to read all of .txt file and save data to array/list. File looks like this:
row11 row12 row13
row21 row22 row23
row31 row32 row33
between strings are only spaces.
Next I will insert data from array/list<> to mysql, but it is not problem.
Thanks.
EDIT: I need insert 3 columns to mysql like .txt file.
Use String.Split(Char[], StringSplitOptions) where the first parameter specifies that you want to split your string using spaces and tabs, and the second parameter specifies that you ignore empty entries (for cases where there are multiple spaces between entries)
Use this code:
var lines = System.IO.File.ReadAllLines(#"D:\test.txt");
var data = new List<List<string>>();
foreach (var line in lines)
{
var split = line.Split(new[]{' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);
data.Add(split.ToList());
}
You can use File.ReadLines() to read the lines from the file, and then Regex.Split() to split each line into multiple strings:
static IEnumerable<String> SplitLines(string path, string splitPattern)
{
foreach (string line in File.ReadAllLines(path))
foreach (string part in Regex.Split(line, splitPattern))
yield return part;
}
To split by white space, you can use the regex pattern \s+:
var individualStrings = SplitLines(#"C:\path\to\file.txt", #"\s+");
You can use the ToList() extension method to convert it to a list:
List<string> individualStrings = SplitLines(#"D:\test\rows.txt", #"\s+").ToList();
As long as there are never spaces in the "values", then a simple line-by line parser will work.
A simple example
var reader = new StreamReader(filePath);
var resultList = new List<List<string>>();
string line;
while ((line = reader.ReadLine()) != null)
{
var currentValues = new List<string>();
// You can also use a StringBuilder
string currentValue = String.Empty;
foreach (char c in line)
{
if (Char.IsWhiteSpace(c))
{
if (currentValue.Length > 0)
{
currentValues.Add(currentValue);
currentValue = String.Empty;
}
continue;
}
currentValue += c;
}
resultList.Add(currentValues);
}
Here's a nifty one-liner based off Amadeusz's answer:
var lines = File.ReadAllLines(fileName).Select(l => l.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries)).SelectMany(words => words);
public static List<string> items = new List<string>() { "a","b","c","d","e" };
I am trying to change each of those from loading a file and replacing with their current inventory.
if (File.Exists("darColItems.txt") == true)
{
char c = ',';
StreamReader st = new StreamReader("darColItems.txt");
temp = st.ReadToEnd().ToCharArray();
foreach (c in temp)
{
}
st.Close();
}
Edit: Taking a file such as: iron,bronze,gold,diamond,iron and taking each name and place it into the list for each spot.
File.txt: "string1","string2","string3","string4","string5"
Startup of program:
List inventory (current):
"a","b","c","d","e"
Load inventory....
List inventory (final):
"string1","string2","string3","string4","string5"
Assuming that you actually want to replace all items in the list with all items in the file in the order of occurence and the delimiter is comma. You could use String.Split:
items = File.ReadAllText("path").Split(new [] { ',' }, StringSplitOptions.None).ToList();
If you have quotes around the words in the file which you want to remove, you can use String.Trim:
items = File.ReadAllText("path")
.Split(new char[] { ',' }, StringSplitOptions.None)
.Select(s => s.Trim('"', ' ')) // remove quotes + spaces at the beginning and end
.ToList();
//keep filename in a constant/variable for easy reuse (better, put it in a config file)
const string SourceFile = "darColItems.txt";
//what character separates data elements (if the elements may contain this character you may instead want to look into a regex; for now we'll keep it simple though, & assume that's not the case
const char delimeter = ',';
//here's where we'll store our values
var values = new List<string>();
//check that our input file exists
if (File.Exists(SourceFile))
{
//using statement ensures file is closed & disposed, even if there's an error mid-process
using (var reader = File.OpenText(SourceFile))
{
string line;
//read each line until the end of file (at which point the line read will be null)
while ((line = reader.ReadLine()) != null)
{
//split the string by the delimiter (',') and feed those values into our list
foreach (string value in line.Split(delimiter)
{
values.Add(value);
}
}
}
}
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.
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