Breaking apart a textblock into strings at a new line - c#

I'm trying to get the content of a textbox, and split it into an array, and then write each line into a file. It looks something like this:
string[] ban = Regex.Split(ImportText.Text, "\r\n");
foreach (string card in ban)
{
if (card != "")
{
string banlist = isoStorage.getSettings("banList");
banlist = "\r\n" + card + banlist;
isoStorage.changeSettings("banList", banlist);
}
ImportText.Text = "";
updateBanListView();
}
The problem is that textbox doesn't return a new line as \r\n. I've tried \n, \r\n, and even environment.newline. I'm using C# on WP7.
Any ideas on how to split my textbox into an array of lines?

For some reason, Windows Phone only uses a carraige return (\r) for a line split in TextBoxes. Two ways you could go about it are.
string[] ban = ImportText.Text.Split('\r');
But that may break if they decide to actually use \n in the future. I've seen another example here doing it this way:
List<string> ban = new List<string>();
string s;
while ((s = reader.ReadLine()) != null)
{
ban.Add(s);
}
Which feels a bit safter

Related

Reading a text file and inserting information into a new object

So I have a text file with information in the following format, with the name, email, and phone number.
Bill Molan, Bill.Molan#gmail.com, 612-789-7538
Greg Hanson, Greg.Hanson#gmail.com, 651-368-4558
Zoe Hall, Zoe.Hall#gmail.com, 952-778-4322
Henry Sinn, Henry.Sinn#gmail.com, 651-788-9634
Brittany Hudson, Brittany.Hudson#gmail.com, 612-756-4486
When my program starts, I want to read this file and make each row into a new Person(), which I will eventually add to a list. I am wanting to read each line, and then use the comma to separate each string to put into the constructor of Person(), which is a basic class:
public PersonEntry(string n, string e, string p)
{
Name = n;
Email = e;
Phone = p;
}
I have done some looking and I think that using a streamreader is going to work for reading the text file, but I'm not really sure where to go from here.
You can use the following method:
string line;
List listOfPersons=new List();
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(#"c:\yourFile.txt");
while((line = file.ReadLine()) != null)
{
string[] words = line.Split(',');
listOfPersons.Add(new Person(words[0],words[1],words[2]));
}
file.Close();
Assuming that the comma will never appear within the data:
Use StreamReader.ReadLine to read each line of text. With each line of text, use string.Split to split the line into an array of strings using the comma as the split character. Now you have an array of 3 strings where [0] is the name, [1] the email, and [2] the phone.
You can read all lines as below // assuming all lines will have 3 values always
var allLines = File.ReadAllLines(path);
var listOfPersons = new List<Person>();
foreach(var line in allLines)
{
var splittedLines = line.Split(new[] {","})
if(splittedLines!=null && splittedLines.Any())
{
listOfPersons.Add( new Person {
Name = splittedLines[0],
Email = splittedLines .Length > 1 ?splittedLines[1]:null,
Phone = splittedLines .Length > 2? splittedLines[2]:null,
});
}
}
this code is a sample must be checked for various conditions like array length etc also please check the

how to split a text in to paragraph with a particular string

I have a long text file ... I read the text file and store the content in a string...
Now I want this text to split. The below is an image which shows what I want.
In the image "This is common text" means this string is common in every paragraph.
Green squares shows that I want that part in string array.
but how o do that... I have tried Regular expression for this... but isn't working....
please help
Try using RegEx.Split() using this pattern:
(.*This is common text.*)
Well, giving priority to RegEx over the string functions is always leads to a performance overhead.
It would be great if you use: (UnTested but it will give you an idea)
string[] lines = IO.File.ReadAllLines("FilePath")
List<string> lst = new List<string>();
List<string> lstgroup = new List<string>();
int i=0;
foreach(string line in lines)
{
if(line.Tolower().contains("this is common text"))
{
if(i > 0)
{
lst.AddRange(lstgroup.ToArray());
// Print elements here
lstgroup.Clear();
}
else { i++; }
continue;
}
else
{
lstgroup.Add(line)
}
}
i = 0;
// Print elements here too
I am not sure what you want to split on but you could use
string[] stringArray = Regex.Split(yourString, regex);
If you want a more concrete example you will have to (as others mentioned) give us more information regardning what the text looks like rather than just "common text".

String Concatenation / Overwriting?

This is a program that reads in a CSV file, adds the values to a dictionary class and then analyses a string in a textbox to see if any of the words match the dictionary entry. It will replace abbreviations (LOL, ROFL etc) into their real words. It matches strings by splitting the inputted text into individual words.
public void btnanalyze_Click(object sender, EventArgs e)
{
var abbrev = new Dictionary<string, string>();
using (StreamReader reader = new StreamReader("C:/Users/Jordan Moffat/Desktop/coursework/textwords0.csv"))
{
string line;
string[] row;
while ((line = reader.ReadLine()) != null)
{
row = line.Split(',');
abbrev.Add(row[0], row[1]);
Console.WriteLine(abbrev);
}
}
string twitterinput;
twitterinput = "";
// string output;
twitterinput = txtInput.Text;
{
char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = twitterinput;
string[] words = twitterinput.Split(delimiterChars);
string merge;
foreach (string s in words)
{
if (abbrev.ContainsKey(s))
{
string value = abbrev[s];
merge = string.Join(" ", value);
}
if (!abbrev.ContainsKey(s))
{
string not = s;
merge = string.Join(" ", not);
}
;
MessageBox.Show(merge);
}
The problem so far is that the final string is outputted into a text box, but only prints the last word as it overwrites. This is a University assignment, so I'm looking for a push in the correct direction as opposed to an actual answer. Many thanks!
string.Join() takes a collection of strings, concatenates them together and returns the result. But in your case, the collection contains only one item: value, or not.
To make your code work, you could use something like:
merge = string.Join(" ", merge, value);
But because of the way strings work, this will be quite slow, so you should use StringBuilder instead.
This is the problem:
string not = s;
merge = string.Join(" ", not);
You are just joining a single element (the latest) with a space delimiter, thus overwriting what you previously put into merge.
If you want to stick with string you need to use Concat to append the new word onto the output, though this will be slow as you are recreating the string each time. It will be more efficient to use StringBuilder to create the output.
If your assignment requires that you use Join to build up the output, then you'll need to replace the target words in the words array as you loop over them. However, for that you'll need to use some other looping mechanism than foreach as that doesn't let you modify the array you're looping over.
Better to User StringBuilder Class for such purpose
http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx

Linebreak in WinForms Textbox

I'm having some trouble dealing with linebreaks here. Basically, the user puts in some data to a textbox that is then saved directly to the database.
When I display the data in my program, I only want to display the first line of the textbox, so I tried
Regex newLine = new Regex("/[\r\n]+/");
String[] lines = newLine.Split(row[data.textColumn.ColumnName].ToString());
SomeLabel.Text = lines[0];
But it display me all lines after another, so if the user puts in
a
b
c
The label displays
abc
How can I get this to work so it only displays the first line?
(I have added this in another answer because this answer is rather large and I think it will make this thread more clear - please leave a comment if I should make it one answer)
I have made this extension method which often have its uses:
public static IEnumerable<string> Lines(this string data)
{
using (var sr = new StringReader(data))
{
string line;
while ((line = sr.ReadLine()) != null)
yield return line;
}
}
And you can get the first line with:
var line = data.Lines().First();
This should be a lot faster than .Split when only a subset of the lines is used.
var data = row[data.textColumn.ColumnName].ToString();
And one of these (both work with unix and windows line-seperators). The first is fastest because it does not split every line when your only using the first.
int min = Math.Min(data.IndexOf("\r\n"), data.IndexOf("\n"));
string line;
if (min != -1)
line = data.Substring(0, min);
else
line = data;
or
var lines = data.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
var line = lines[0];
(See also a few extension methods I have posted here: How can I convert a string with newlines in it to separate lines?)

parse lines using linq to txt

var t1 = from line in File.ReadAllLines(#"alkahf.txt")
let item = line.Split(new string[] {". "}, StringSplitOptions.RemoveEmptyEntries)
let verse = line.Split(new string[] { "\n. " }, StringSplitOptions.RemoveEmptyEntries)
select new
{
Index = item,
Text = verse
};
having problems with above code im unsure how to parse the lines properly.
the format of the file is like so, I would also like to ignore any empty lines
StringSplitOptions.RemoveEmptyEntries doesn't work for some reason
1. This is text it might have numbers
2. I skipped a line
In the LINQ part, you are inside a single line, so you might want to exclude the empty lines first:
from line in File.ReadAllLines(#"alkahf.txt")
where !string.IsNullOrEmpty(line)
You then do two splits - one on newline, which is odd (since that won't be there, since we know we are reading lines). I expect you mean something like:
let parts = line.Split('.')
where parts.Length == 2
select new {
Index = parts[0],
Text = parts[1]
};
?
Also, note that ReadAllLines is a buffered operation; if you want true streaming, you might want something like:
public static IEnumerable<string> ReadLines(string path) {
using(var reader = File.OpenText(path)) {
string line;
while((line = reader.ReadLine()) != null) {
yield return line;
}
}
}
which is not buffering (you don't load the entire file at once). Just change the first line to:
from line in ReadLines(#"alkahf.txt")
Thanks to Marc's answer I fixed my issue. Sorry for the late response I'm working on this as a personal project.
The code is like so
var t1 = from line in StreamReaderExtension.ReadLinesFromFile(#"alkahf.txt")
let parts = line.Split(new string[]{". "},
StringSplitOptions.RemoveEmptyEntries)
where !string.IsNullOrEmpty(line)
&& int.Parse(parts[0].ToString()).ToString() != ""
select new
{
Index = parts[0],
Text = parts[1]
};
The int parse addition makes sure that the input is returning an integer, if you're using this code it's a good idea to set a flag in case it picks ups a non-integer or it will go unnoticed.

Categories

Resources