How can I display a string array in a textbox? - c#

private void SplitString()
{
ArrayList splitted = new ArrayList();
string[] words = richTextBox1.Text.Split(new char [] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
var word_query =
(from string word in words
orderby word
select word).Distinct();
string[] result = word_query.ToArray();
foreach(string results in result)
{
richTextBox2.Text = results;
}
}
I wrote a form application for taking a text file and splitting strings at the file. And the final purpose is writing unique strings on textbox. The problem is strings flow quickly on textbox but i like to stand them on textbox.

You are iterating your array and assigning each time so textbox will have only last item of the array.
You just to join your array and display in the textbox in following way :
string[] result = word_query.ToArray();
richTextBox2.Text = String.Join(",",result); // You can use any string as separator.

If you want each string to appear in the text box on a separate line, just assign the array of strings to the Lines property, like so:
richTextBox2.Lines = result;

Related

How to split a string in a listbox and showing it in another listbox

I opened a text file and showed it in a listbox (lstArchivo) every string is divided by a semi colon (;) i'm trying to split every string in that listbox (lstArchivo) that has the semicolon. The problem i'm having is that when i display the new splitted list in listbox1 the output i get is String[] Array in every item. Is it better to split every string reading from textfile directly or reading from listbox?
string[] strFields;
string strLine;
char[] charDelimiter = { ';' };
foreach(string item in lstArchivo.Items)
{
strLine = lstArchivo.Items.ToString();
strFields = strLine.Split(charDelimiter);
listBox1.Items.Add(strFields);
}
this is the code i have
You could use code like this:
char[] charDelimiter = { ';' };
foreach(string item in lstArchivo.Items)
{
strFields = item.Split(charDelimiter);
listBox1.Items.Add(strFields[0]);
}
Note that we are splitting on "item" from your foreach loop.

C# Syntax - Remove last occurrence of ';' in string from split

I have a list of strings stored in an ArrayList. I want to split them by every occurrence of ';'. The problem is, whenever I try to display them using MessageBox, there's an excess space or unnecessary value that gets displayed.
Sample input (variable = a):
Arial;16 pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;
Below is a line of code I used to split them:
string[] display_document = (a[0] + "").Split(';');
Code to display:
foreach (object doc_properties in display_document)
{
TextBox aa = new TextBox();
aa.Font = new Font(aa.Font.FontFamily, 9);
aa.Text = doc_properties.ToString();
aa.Location = new Point(pointX, pointY);
aa.Size = new System.Drawing.Size(80, 25);
aa.ReadOnly = true;
doc_panel.Controls.Add(aa);
doc_panel.Show();
pointY += 30;
}
The output that displays are the following:
How do I remove the last occurrence of that semicolon? I really need help fixing this. Thank you so much for all of your help.
Wouldnt It be easiest to check if the input ends with a ";" before splitting it, and if so remove the last character? Sample code:
string a = "Arial;16 pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;";
if (a.EndsWith(";"))
{
a = a.Remove(a.LastIndexOf(";"));
}
//Proceed with split
Split will not print last semicolon if no space character is added and your input is a string.
I don't know why you prefer an array list (which probably is the reason of this strange behaviour) but if you could use your input as a string you could try that
string a = "Arial;16pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;";
string[] display_document = a.Split(';');
foreach (object doc_properties in display_document)
{
//The rest of your code
}

Getting the last part of elements when splitting a string

Here's what I'm trying to workout split function.
The com is a string passed from a textbox, and it removes the first piece from the text.
The text in the textbox is being pass as this ".fedex TYU-123 Time to pick up package"
Then, when gms is part of the first piece of the strip[] array.
string format = com.Remove(0,1);
string[] strip = format.Split(new string[] { " " }, StringSplitOptions.None);
if (strip[0] == "gsm")
{
string carrier = strip[0];
string trackid = strip[1];
string message = strip[2];
}
strip[2] only contains "Time". I wanted to return the last part as this: "Time to pick up package".
Keep in mind also, since the message will be different at times as well, so I don't want a specific string search.
How can I achieve this?
It sounds like you only want to split the first three elements.
Split() has an overload that lets you tell it how many items to return:
format.Split(new[] { ' ' }, 3)
I assume you want all words starting with the third, use string.Join(" ", strip.Skip(2)):
string[] strip = format.Split(new string[] { " " }, StringSplitOptions.None);
if (strip[0] == "gsm")
{
string carrier = strip[0];
string trackid = strip[1];
string message = string.Join(" ", strip.Skip(2)); //Time to pick up package
}
You can use the string.Split(char[], int32) method for this, in which you can give a max. number of splitted strings to return.
So:
format.Split(new[] {' '}, 3);
would do the trick.
More info: http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx

Substring values into multiple textboxes

I want to seperate multiple values from a gridview control and show it in four textboxes. Is that possible?
Right now I get this value:
With this code:
var lblRef = new Label
{
Text = ((Label) row.FindControl("LabelAssignmentReference")).Text
};
string valueTextBox = lblRef.Text;
int indexOfRefSwe = valueTextBox.IndexOf(",", StringComparison.Ordinal);
string valueRef = valueTextBox.Substring(0, indexOfRefSwe);
TextBoxReference.Text = valueRef;
But how do i get it in multiple values? ` TextBoxReference.Text = valueRef;
TextBoxRefPhone.Text = "??";
TextBoxRefEmail.Text = "??";
TextBoxRefDesc.Text = "??";`
This should get you started.
string[] splits = lblRef.Text.Split(',');
Console.WriteLine(splits[0]); // refname
Console.WriteLine(splits[1]); // 08712332
Console.WriteLine(splits[2]); // ref#gmail.com
Console.WriteLine(splits[3]); // refdescription
I suggest also adding validation checks to make sure you don't get any errors, such as checking that splits.Length == 4 as expected.
Note that the spaces will be included in the beginning of the last three elements of splits. You can eliminate those using the Trim method, or by providing an array of delimiters new[] {',', ' '} to the split function and ignore empty elements (there's an overload for that).
There is System.String.Split()-method:
string[] parts = str.Split(new char[] {','});
Afterwards, work on the parts.
Example from MSDN
using System;
public class SplitTest {
public static void Main() {
string words = "This is a list of words, with: a bit of punctuation" +
"\tand a tab character.";
string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });
foreach (string s in split) {
if (s.Trim() != "")
Console.WriteLine(s);
}
}
}
you can do as below
var values = lblRef.Text.Split(',');
TextBoxRefPhone.Text = values[0];
if(values.Length>0)
TextBoxRefEmail.Text =values[1];
if(values.Length>1)
TextBoxRefDesc.Text = values[2];
Edit
there is a Split overload method which accept params. so we can give one character
public string[] Split(params char[] separator);
The params keyword lets you specify a method parameter that takes an
argument where the number of arguments is variable.

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

Categories

Resources