Substring values into multiple textboxes - c#

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.

Related

C# Sorting element inside an array

I'm trying to do a sorting for my result.
Eg: result = 04,07,01,57,83,39 Expect: result = 01,04,07,39,57,83
I have been try use array.sort, but the result will be return like ,,,,,00013345778
So is there any solution to get my expect result?
This is the code I try to do:
String result = 04,07,01,57,83,39;
Sorting(result);
public static string Sorting(string input)
{
char[] characters = input.ToArray();
Array.Sort(characters);
return new string(characters);
}
It is ambiguous whether the original data is a string or an integer.
If it's an integer, #Carlos Jafet Neto's answer would be appropriate.
If it is a character string, it will be as follows.
static void Main(string[] args)
{
String result = "04,07,01,57,83,39";
Console.WriteLine(Sorting(result));
}
public static string Sorting(string input)
{
string[] characters = input.Split(',');
Array.Sort(characters);
return string.Join(',',characters);
}
You can do something like this:
public static void Main()
{
int[] arr = new int[] {04,07,01,57,83,39};
Array.Sort(arr);
foreach(int value in arr)
{
Console.Write(value + " ");
}
}
I notice two things you are missing in your code: the brackets in the array declaration as string[ ] or int[ ], and to declare an array literal, the syntax is like this:
string[] values = {"one", "two", "three", "four"};
First of all, there is a compilation error in your code (string literal should be enclosed in "" like "this is c# string")
Second of all, when you perform ToArray() on your string you get back an array of characters which is the following for this string "01, 02, 03": ['0', '1', ',', ' ', '0', '2', ',', ' ', '0', '3'].
So to sort this string as an array of integers you first should convert it to an array of integers like this:
int[] sorted = str.Split(',')
.Select(s => int.Parse(s.Trim()))
.OrderBy(val => val)
.ToArray();
Or as correctly noticed #kunif in his answer you may sort array of strings after Split (without parsing in to int) if you need get back a string rather than an integers array. Notice however that if in your string there are values with different length like 153 and 16, this may lead to incorrect results, because strings are sorted character by character and since '5' is less than '6', "153" is less than "16". I guess you added leading zeros to your values to prevent this problem from happening. So the right answer actually depends on your needs.

C# textfile create / remove spacing of texts in same line

what can I do to achieve the output on right side as shown on image? Do note that later on there will be many data with this kind of inconsistent alignment and is there any way to loop all text along with adjusted alignment as shown on right side of image?
You could use Regex to replace occurrence of multiple whitespace (2 or more,including tab) with a single whitespace. For example,
var result = Regex.Replace(str,"[\t ]{2,}"," ");
The common forms of whitespace could divided into
Space
Tab(\t)
NewLine(\n)
Return(\t)
In the above scenario, it looks like you need to replace all the Space (2 or more) and Tab characters with a single whitespace character (and ignore the NewLine/Return characters). For the purpose, you could use Regex as shown in the code above
Short Answer, use Trim() or TrimEnd, but here is the way I would do your task using my Nuget package you can convert this to string.Split() if you don't want to use a Nuget package:
Nuget Package:
DataJuggler.Core.UltimateHelper (.Net Framework)
DataJuggler.UltimateHelper.Core (.Net Core)
.Net Framework is shown
// source input
string inputFileText = "blah blah blah blah blah " + Environment.NewLine + "blah blah blah blah blah";
// parse the lines
List<TextLine> lines = WordParser.GetTextLines(inputFileText);
// If the lines collection exists and has one or more items
if (ListHelper.HasOneOrMoreItems(lines))
{
// Iterate the collection of TextLine objects
foreach (TextLine line in lines)
{
// Get the words
List<Word> words = WordParser.GetWords(line.Text);
}
}
Then you can do what you want with each Line, and each Line contains a list of Words (string text).
Here is the code the Nuget package uses, if you would rather copy it:
public static List<TextLine> GetTextLines(string sourceText)
{
// initial value
List<TextLine> textLines = new List<TextLine>();
// typical delimiter characters
char[] delimiterChars = Environment.NewLine.ToCharArray();
// local
int counter = -1;
// verify the sourceText exists
if (!String.IsNullOrEmpty(sourceText))
{
// Get the list of strings
string[] linesOfText = sourceText.Split(delimiterChars);
// now iterate the strings
foreach (string lineOfText in linesOfText)
{
// local
string text = lineOfText;
// increment the counter
counter++;
// add every other row
if ((counter % 2) == 0)
{
// Create a new TextLine
TextLine textLine = new TextLine(text);
// now add this textLine to textLines collection
textLines.Add(textLine);
}
}
}
// return value
return textLines;
}
public static List<Word> GetWords(string sourceText, char[] delimeters = null, bool allowEmptyStrings = false)
{
// initial value
List<Word> words = new List<Word>();
// typical delimiter characters
char[] delimiterChars = { ' ','-','/', ',', '.', '\t' };
// if the delimter exists
if (NullHelper.Exists(delimeters))
{
// use these delimters
delimiterChars = delimeters;
}
// verify the sourceText exists
if (!String.IsNullOrEmpty(sourceText))
{
// Get the list of strings
string[] strings = sourceText.Split(delimiterChars);
// now iterate the strings
foreach(string stringWord in strings)
{
// verify the word is not an empty string or a space
if ((allowEmptyStrings) || (TextHelper.Exists(stringWord)))
{
// Create a new Word
Word word = new Word(stringWord);
// now add this word to words collection
words.Add(word);
}
}
}
// return value
return words;
}

How can I display a string array in a textbox?

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;

C# How to delete every character after something on every line

So I've been trying to figure out how to delete characters after a certain point on each line, for example I have a list like:
dskfokes=dasfn3rewk
dsanfiwen=434efsde
damkw4343=o3rm3i
dmfkim303rk2=0439wefksd
32i32j9esfj=42393jdsf
How would I go about deleting everything on each line after '='?
Use string.IndexOf() to get the index of the char you want to remove, then string.Remove() to do the removing.
string str = "dskfokes=dasfn3rewk";
str = str.Remove(str.IndexOf('='));
One approach is to use LINQ:
var strings = new string[] {
"dskfokes=dasfn3rewk
, "dsanfiwen=434efsde
, "damkw4343=o3rm3i
, "dmfkim303rk2=0439wefksd
, "32i32j9esfj=42393jdsf
};
var res = strings.Select(s => s.Split('=')[0]).ToArray();
This splits each string on =, and drops everything after the first '=' character if it is there.
You may also do it using String.Split() like
string[] allWords = new string[] {
"dskfokes=dasfn3rewk",
"dsanfiwen=434efsde",
"damkw4343=o3rm3i",
"dmfkim303rk2=0439wefksd",
"32i32j9esfj=42393jdsf"
};
foreach(string s in allWords)
{
string[] urstring = s.Split('=');
Console.WriteLine(urstring[0]);
}
I suggest you to use a combination of string handling operations SubString and IndexOf to achieve this, consider the example:
List<string> inputLine = new List<string>(){ "dskfokes=dasfn3rewk",
"dsanfiwen=434efsde",
"damkw4343=o3rm3i",
"dmfkim303rk2=0439wefksd",
"32i32j9esfj=42393jdsf"};
List<string> outputLines = inputLine.Select(x =>
x.IndexOf('=') == -1 ? x :
x.Substring(0, x.IndexOf('='))).ToList();
Note : The IndexOf will return -1 if the specified index was not found, in such cases substring method will throws errors since -1 will not be a valid index. So we have to check for existence of index withing the string before proceeding. you can also try simple foreach as like this:
List<string> outputLines=new List<string>();
int currentCharIndex=-1;
foreach (string line in inputLine)
{
currentCharIndex = line.IndexOf('=');
if(currentCharIndex ==-1)
outputLines.Add(line);
else
outputLines.Add(line.Substring(0,currentCharIndex));
}

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