I have a string which looks like this:
Less than $5,000, $5,000-$9,999, $10,000-$14,999, $45,000-$49,999, $50,000-$54,999
And what I would like to have is:
Less than $5,000 or $5,000-$9,999 or $10,000-$14,999 or $45,000-$49,999 or $50,000-$54,999
What I tried is:
items[1].Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(e => new AnswerModel { Name = e }).ToList()
Name should be "Less than $5,000" then "$5,000-$9,999" and so on.
But it splits by every comma, I would need to split it first by the second and then by the third.
What would be the best approach?
Maybe you can split by ", "
string s = "Less than $5,000, $5,000-$9,999, $10,000-$14,999, $45,000-$49,999, $50,000-$54,999";
string result = string.Join(" or ", s.Split(new []{", "},StringSplitOptions.None));
Returns your desired result:
Less than $5,000 or $5,000-$9,999 or $10,000-$14,999 or
$45,000-$49,999 or $50,000-$54,999
If your string looks exactly as you pasted here, and it will always have such pattern, then you can split on a string of two characters:
items[1].Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
Update:
But if your string is without spaces, then you should replace first with some unique character like |, and then split over that new character:
items[1].Replace(",$", "|$").Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries);
Also you can replace it with or $ and the string would be already in desired format, and there would be no need to split and join again.
This should do the trick.
Related
So i have a String like so
String org = "Go to http://Apple.com, to see the new Ipad";
How do i return a list of all the words in the String including the url?
For example. The above string should return this list
List<String> chopped = new List<String>(){"Go", "to", "http://Apple.com", " to", "see" , " the", " new", " Ipad"};
I am doing this because i want to reconstruct the string but use the link for something else.
Use string.Split method:
string[] chopped = org.Split(' ');
It returns array of string instead of List<string>.
But you'll still have to take care of characters like ,. You can try doing following:
string []chopped = org.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
It will split using both a space and a comma and return results ignoring empty ones.
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
Given the c# code:
string foo = #"
abcde
fghijk";
I am trying to remove all formatting, including whitespaces between the lines.
So far the code
foo = foo.Replace("\n","").Replace("\r", "");
works but the whitespace between lines 2 and 3 and still kept.
I assume a regular expression is the only solution?
Thanks.
I'm assuming you want to keep multiple lines, if not, i'd choose CAbbott's answer.
var fooNoWhiteSpace = string.Join(
Environment.NewLine,
foo.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Select(fooline => fooline.Trim())
);
What this does it split the string into lines (foo.Split),
trim whitespace from the start and end of each line (.Select(fooline => fooline.Trim())),
then combine them back together with a new line inbetween (string.Join).
You could use a regular expression:
foo = Regex.Replace(foo, #"\s+", "");
How about this?
string input = #"
abcde
fghijk";
string output = "";
string[] parts = input.Split('\n');
foreach (var part in parts)
{
// If you want everything on one line... else just + "\n" to it
output += part.Trim();
}
This should remove everthing.
If the whitespace is all spaces, you could use
foo.Replace(" ", "");
For any other whitespace that may be in there, do the same. Example:
foo.Replace("\t", "");
Just add a Replace(" ", "") your dealing with a string literal which mean all the white space is part of the string.
Try something like this:
string test = #"
abcde
fghijk";
EDIT: Addded code to only filter out white spaces.
string newString = new string(test.Where(c => Char.IsWhiteSpace(c) == false).ToArray());
Produces the following: abcdefghijk
I've written something similar to George Duckett but put my logic into a string extension method so it easier for other to read/consume:
public static class Extensions
{
public static string RemoveTabbing(this string fmt)
{
return string.Join(
System.Environment.NewLine,
fmt.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Select(fooline => fooline.Trim()));
}
}
you can the call it like this:
string foo = #"
abcde
fghijk".RemoveTabbing();
I hope that helps someone
it returns not what i expected.
i expected something like:
ab
cab
ab
what am i doing wrong?
don't do .ToCharArray()
it will split \r then \n
that why you have empty value
something like this should work
var aa = ("a" & Environment.NewLine & "b" & Environment.NewLine & "c").Split(New String[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
Since you are splitting on "\r" and "n", String.Split extracts the empty string from "\r\n".
Take a look at StringSplitOptions.RemoveEmptyEntries or use new String[] { "\r\n" } instead of "\r\n".ToCharArray().
You just splitting the string using \r or \n as delimiters, not the \r\n together.
Environment.NewLine is probably the way to go but if not this works
var ab = "a\r\nb\r\nc";
var abs = ab.Split(new[]{"\r\n"}, StringSplitOptions.None);
This option also works,
string [] b = Regex.Split(abc, "\r\n");
My understanding is that the string char sequence you provide to the Split method is a list of delimiter characters, not a single delimiter madeof several characters.
In your case, Split consider the '\r' and '\n' characters as delimiters. So when it encounters the '\r\n' sequence, it returns the string between those 2 delimiters, an empty string.
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);