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
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(' ');
I have a simple .txt file with X,Y-values in it. It is structured like this:
-25.7754 35.87
-22.1233 32.16
-20.361 30.75
etc.
I am able to read single lines or the whole text to the end, with objstream.ReadToEnd(); & objstream.ReadLine().
But here's my question how could I indicate when the String after the first value ends so I can save/parse it to float & proceed reading the value of the next string?
Here is the read functionality I have so far :)
StreamReader objStream = new StreamReader("C:blablabla\\Text.asc");
textBox1.Text = objStream.ReadLine();
Thanks in advance,
BC++
Use String.split()
As requested, an example :
string s = "there is a cat";
//
// Split string on spaces.
// ... This will separate all the words.
//
string[] words = s.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
}
The output is :
there
is
a
cat
Look at the string.Split methods:
var line1 = objStream.ReadLine();
var lineParts = line1.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
textBox1.Text = lineParts[0];
textBox2.Text = lineParts[1];
Note the use of an overload that uses StringSplitOptions.RemoveEmptyEntries - the means that if you have multiple spaces in succession, the result will not contain empty entries.
If you really mean white-space and not space then you have to go this way:
string line = "-25.7754 35.87";
string[] values = line.Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries);
The difference from the other answers in the splitting character. If this not defined then white-space characters are assumed to be the delimiters. In other words you will get the same result for
string line = "-25.7754\t35.87"; // tab instead of spaces.
You will have the flexibility to split correctly fixed length or tab delimited lines using the same code.
today I was wondering if there is a better solution perform the following code sample.
string keyword = " abc, foo , bar";
string match = "foo";
string[] split= keyword.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string s in split)
{
if(s.Trim() == match){// asjdklasd; break;}
}
Is there a way to perform trim() without manually iterating through each item? I'm looking for something like 'split by the following chars and automatically trim each result'.
Ah, immediatly before posting I found
List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
in How can I split and trim a string into parts all on one line?
Still I'm curious: Might there be a better solution to this? (Or would the compiler probably convert them to the same code output as the Linq-Operation?)
Another possible option (that avoids LINQ, for better or worse):
string line = " abc, foo , bar";
string[] parts= Array.ConvertAll(line.Split(','), p => p.Trim());
However, if you just need to know if it is there - perhaps short-circuit?
bool contains = line.Split(',').Any(p => p.Trim() == match);
var parts = line
.Split(';')
.Select(p => p.Trim())
.Where(p => !string.IsNullOrWhiteSpace(p))
.ToArray();
I know this is 10 years too late but you could have just split by ' ' as well:
string[] split= keyword.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
Because you're also splitting by the space char AND instructing the split to remove the empty entries, you'll have what you need.
If spaces just surrounds the words in the comma separated string this will work:
var keyword = " abc, foo , bar";
var array = keyword.Replace(" ", "").Split(',');
if (array.Contains("foo"))
{
Debug.Print("Match");
}
I would suggest using regular expressions on the original string, looking for the pattern "any number of spaces followed by one of your delimiters followed by one or more spaces" and remove those spaces. Then split.
Try this:
string keyword = " abc, foo , bar";
string match = "foo";
string[] split = Regex.Split(keyword.Trim(), #"\s*[,;]\s*");
if (split.Contains(match))
{
// do stuff
}
You're going to find a lot of different methods of doing this and the performance change and accuracy isn't going to be readily apparent. I'd recommend plugging them all into a testing suite like NUnit in order both to find which one comes out on top AND which ones are accurate.
Use small, medium, and large amounts of text in loops to examine the various situations.
Starting with .Net 5, there is an easier option:
string[] split= keyword.Split(new char[] { ',', ';' }, StringSplitOptions.TrimEntries);
You can combine it with the option to remove empty entries:
string[] split= keyword.Split(new char[] { ',', ';' }, StringSplitOptions.TrimEntries | 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)