I have a program in which I read from a string that's formatted to have a specific look.
I need the numbers which are separated by a comma (e.g. "A,B,D,R0,34,CDF"->"A","B","D","R0", "34", "CDF").
There are commas between letters that much is guaranteed
I have tried to do (note: "variables" is a 2D char array, newInput is a string which is a method argumend, k and j are declared and defined as 0)
for(int i=0; i<=newInput.Length; i++){
while(Char.IsLetter(newInput[i])){
variables[k,j]=(char)newInput[i];
i++;
k++;
}
k=0;j++;
}
with multi-dimensional character arrays.
Is there a way for this to be done with strings? Because char arrays conflict with many parts of the program where this method has already been implemented
Simple. Just use the Split method:
var input = "A,B,D,R0,34,CDF";
var output = input.Split(','); // [ "A", "B", "D", "R0", "34", "CDF" ]
Try this:
string MyString="A,B,D,R0,34,CDF";
string[] Parts = MyString.Split(',');
And use them like:
Parts[0];//A
Parts[1];//B
Parts[2];//D
Parts[3];//R0
Parts[4];//34
Parts[5];//CDF
If you want to know more about Split function. Read this.
if you want to Split the string on line breaks use this
string str = "mouse\r\dog\r\cat\r\person\r\pig";
string[] lines = Regex.Split(str, "\r\n");
and if you want to split with chars , as input ,Split takes array of chars
char[] myChars = {':', ',', '.', '\u', ' ' };
string myString = "jack:tom kasra\unikoo car,pencil ball";
string[] myWords = myString.Split(myChars);
Related
user1;user2;user3;user4 user1
I'd like to split these strings so I can iterate over all of them to put them in objects. I figured I could use
myString.split(";")
However, in the second example, there is no ; , so that wouldn't do the trick. What would be the best way to do this when it can be variable like this?
Thanks
You can use overload taking multiple separators:
myString.Split(new[] { ";", " " }, StringSplitOptions.RemoveEmptyEntries);
No need for a regex. The split method can take a list of separators
"user1;user2;user3;user4 user1".Split(';', ' ')
outputs
string[5] { "user1", "user2", "user3", "user4", "user1" }
You can use the regex
"[ ;]"
the square brackets define a character class - matches one of the characters between the brackets.
You can use overload of Split() method which take an array of seperator
string myString = "user1;user2;user3;user4 user1";
string[] stringSeparators = new string[] { ";", " " };
string[] s = myString.Split(stringSeparators, StringSplitOptions.None);
the following test pass!
[TestCase("user1;user2;user3;user4 user1", 5)]
public void SplitString(string input, int expectedCount)
{
Assert.AreEqual(expectedCount, input.Split(new []{";"," "},StringSplitOptions.RemoveEmptyEntries));
}
Can anyone help with a little code i want to make array which first index will have first word of textbox text:
array[0] first word of text
array[1] second word of text
can anyone help me?
string str = "Hello Word Hello" ;
var strarray = str.Split(' ') ;
You can replace the str with TextBox.Text...
Use the Split method of the string type.
It will split your string by a character specification to a string array (string[]).
For example:
textBox1.Text = "The world is full of fools";
string[] words = textBox1.Text.Split(' ');
foreach(string word in words)
{
//iterate your words here
}
If they are seperated by spaces :
var MyArray = MyTextBox.Text.Split(' ');
There's a very simple way of doing this:
string text = "some text sample";
List<string> ltext = text.Split(' ').ToList();
U can use the split method,it gets a string array back,you need to pass a char array with the characters to split upon:
string[] str = textBox1.Text.Split(new char[] { ' ', ',', ':', ';', '.' });
use .Split() method like this:
var array = textboxText.Split(' ');
Hi guys I have a problem at hand that I can't seem to figure out, I have a string (C#) which looks like this:
string tags = "cars, motor, wheels, parts, windshield";
I need to break this string at every comma and get each word assign to a new string by itself like:
string individual_tag = "car";
I know I have to do some kind of loop here but I'm not really sure how to approach this, any help will be really appreciate it.
No loop needed. Just a call to Split():
var individualStrings = tags.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
You can use one of String.Split methods
Split Method (Char[])
Split Method (Char[], StringSplitOptions)
Split Method (String[], StringSplitOptions)
let's try second option:
I'm giving , and space as split chars then on each those character occurrence input string will be split, but there can be empty strings in the results. we can remove them using StringSplitOptions.RemoveEmptyEntries parameter.
string[] tagArray = tags.Split(new char[]{',', ' '},
StringSplitOptions.RemoveEmptyEntries);
OR
string[] tagArray = s.Split(", ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);
you can access each tag by:
foreach (var t in tagArray )
{
lblTags.Text = lblTags.Text + " " + t; // update lable with tag values
//System.Diagnostics.Debug.WriteLine(t); // this result can be see on your VS out put window
}
make use of Split function will do your task...
string[] s = tags.Split(',');
or
String.Split Method (Char[], StringSplitOptions)
char[] charSeparators = new char[] {',',' '};
string[] words = tags.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
string[] words = tags.Split(',');
You are looking for the C# split() function.
string[] tags = tags.Split(',');
Edit:
string[] tag = tags.Trim().Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
You should definitely use the form supplied by Justin Niessner. There were two key differences that may be helpful depending on the input you receive:
You had spaces after your ,s so it would be best to split on ", "
StringSplitOptions.RemoveEmptyEntries will remove the empty entry that is possible in the case that you have a trailing comma.
Program that splits on spaces [C#]
using System;
class Program
{
static void Main()
{
string s = "there, is, a, cat";
string[] words = s.Split(", ".ToCharArray());
foreach (string word in words)
{
Console.WriteLine(word);
}
}
}
Output
there
is
a
cat
Reference
I have a string like this string strings=" black door,white door,red door "
Now I want to put this string into array.
I use split myarray = strings.split(',') then array look like this: black,door,white,door,red,door.
I want to put the string into the array after each occurance of comma not on the space. I want it like this in the array:
black door,white door,red door.
if you have "black door,white door,red door" string then use only , as separator
var result = "black door,white door,red door".Split(',');
use split like this
var result = myString.Split(',');
It will split only on , and not the whitespace, and should give you the expected result.
use ',' as separator:
s.Split(',');
You need:
var array = input.Split(',');
ToArray() was unnecessary.
string s = "black door,white door,red door";
string[] sarr;
sarr = s.Split(',');
Could you post your own code in its entirety? It seems we all agree that this is the proper way to do it.
Have you tried iterating through the array and printing out the values?
string strings = "black door,white door,red door";
string[] myarray = strings.Split(',');
foreach (string temp in myarray)
{
MessageBox.Show(temp);
}
Try this:
string input = "black door,white door,red door";
string[] values = input.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
i am having trouble splitting a string in c# with a delimiter of "][".
For example the string "abc][rfd][5][,][."
Should yield an array containing;
abc
rfd
5
,
.
But I cannot seem to get it to work, even if I try RegEx I cannot get a split on the delimiter.
EDIT: Essentially I wanted to resolve this issue without the need for a Regular Expression. The solution that I accept is;
string Delimiter = "][";
var Result[] = StringToSplit.Split(new[] { Delimiter }, StringSplitOptions.None);
I am glad to be able to resolve this split question.
To show both string.Split and Regex usage:
string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, #"\]\[");
string tests = "abc][rfd][5][,][.";
string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);
Another option:
Replace the string delimiter with a single character, then split on that character.
string input = "abc][rfd][5][,][.";
string[] parts1 = input.Replace("][","-").Split('-');
Regex.Split("abc][rfd][5][,][.", #"\]\]");
More fast way using directly a no-string array but a string:
string[] StringSplit(string StringToSplit, string Delimitator)
{
return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}
StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/
In .NETCore 2.0 and beyond, there is a Split overload that allows this:
string delimiter = "][";
var results = stringToSplit.Split(delimiter);
Split (netcore 2.0 version)