split string to three doubles - c#

I used C# and I would like split text comprised 3 doubles seperated by commas and spaces.
I did:
double[] doubles = mystr.Trim().Split(new char[] { ' ', ',' })
.Select(s => Convert.ToDouble(s))
.ToArray();
when mystr = 33,44,55 for example it works fine (numbers seperated by only one comma)
Also, when mystr= 33 44 55 for example it works fine (numbers seperated by only one space)
BUT, when mystr= 33, 44, 55 it doesn't works (one space after the comma between each two numbers)
It also doesn't work when mystr = 33 44 55 (two spaces between each two numbers)
In both above examples I got an unhandled exception.
How can I solve it?
Thanks!

You can add an option to remove empty entries in the Split:
var array = Array.ConvertAll(mystr.Split(new [] { ' ', ',' },
StringSplitOptions.RemoveEmptyEntries),
Convert.ToDouble);

You could use System.Text.RegularExpressions.Regex:
var pattern = #"(\d+)((,\s*|\s+)|$)";
const int RegexTimeoutSeconds = 1;
var matches = Regex.Matches(mystr, pattern, RegexOptions.None, TimeSpan.FromSeconds(RegexTimeoutSeconds));
var doubles = new List<double>();
foreach (Match match in matches)
{
var group = match.Groups[1];
var d = Convert.ToDouble(group.Value);
doubles.Add(d);
}

Just try specifying StringSplitOptions, and use StringSplitOptions.RemoveEmptyEntries to remove empty strings..
double[] doubles = mystr.Trim().Split(new char[] { ' ', ',' },StringSplitOptions.RemoveEmptyEntries)
.Select(Convert.ToDouble)
.ToArray();

Related

Best way to change this String-line into multiple Int's?

I have some strings that looke like this:
"97-145, 3-5, 77-87, 5-10"
i need every value (97, 145, 3, 5, 77, 97, 5 and 10) stored in different int variables.
I started by trying to go through the string for each character and search for '-' or ',' but unfortunately this doesn't works for all lines, because some look like this:
"97, 3, 77-87, 5-10"
so in this case, when i search for the next '-' after i stored the first value (97), it will search until it finds the next '-' character and then stores 87.
is there a better way to solve this?
You could easily do it using a Split, assuming its always - or ,:
string str = "97-145, 3-5, 77-87, 5-10";
var ints = str.Split(new string[] { "-", "," }, StringSplitOptions.None).Select(int.Parse).ToArray();
foreach (int i in ints) Console.WriteLine(i);
Which gives:
97
145
3
5
77
87
5
10
Demo: https://dotnetfiddle.net/zE0LtW
Assuming you don't need decimals, you can easily achieve this using Regex. Specifically, match \d+ and that should find all number groups. Then simply parse each group Int32.Parse or Int32.TryParse and you're done.
Here's a sample of the regex parsing: https://regex101.com/r/YrHtY5/1
Here's a quick code sample:
var input = "97-145, 3-5, 77-87, 5-10";
var regex = new Regex("\\d+");
var regexMatches = regex.Matches(input);
var results = new List<int>();
foreach(Match match in regexMatches)
results.Add(Int32.Parse(match.Value));
I replace - by , in the string and I split:
string s = "97-145, 3-5, 77-87, 5-10";
string[] sArray = s.Replace("-", ",").Split(',');
int[] iArray = Array.ConvertAll(sArray, int.Parse);
foreach (int i in iArray) {
Console.WriteLine(i);
}
But you can also split with {'-', ','}

How to remove Whitespce from stringArray formed based on whitespace

I have a string which contains value like.
90 524 000 1234567890 2207 1926 00:34 02:40 S
Now i have broken this string into string Array based on white-space.Now i want to create one more string array into such a way so that all the white-space gets removed and it contains only real value.
Also i want to get the position of the string array element from the original string array based on the selection from the new string array formed by removing white space.
Please help me.
You can use StringSplitOptions.RemoveEmptyEntries via String.Split.
var values = input.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries: The return value does not include array elements that contain an empty string
When the Split method encounters two consecutive white-space it will return an empty string.Using StringSplitOptions.RemoveEmptyEntries will remove the empty strings and give you only the values you want.
You can also achieve this using LINQ
var values = input.Split().Where(x => x != string.Empty).ToArray();
Edit: If I understand you correctly you want the positions of the values in your old array. If so you can do this by creating a dictionary where the keys are the actual values and the values are indexes:
var oldValues = input.Split(' ');
var values = input.Split().Where(x => x != string.Empty).ToArray();
var indexes = values.ToDictionary(x => x, x => Array.IndexOf(oldValues, x));
Then indexes["1234567890"] will give you the position of 1234567890 in the first array.
You can use StringSplitOptions.RemoveEmptyEntries:
string[] arr = str.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
Note that i've also added tab character as delimiter. There are other white-space characters like the line separator character, add as desired. Full list here.
string s = "90 524 000 1234567890 2207 1926 00:34 02:40 S ";
s.Split(' ').Where(x=>!String.IsNullOrWhiteSpace(x))

Splitting on ; then on =, having issues using String.Split, regex required

"key1"="value1 http://www.example.com?a=1";"key2"="value2 http://www.example.com?a=2";
I need to split the above line 2 times, the first time it is the comma character ; and the second time on the = sign.
It doesn't work correctly because the value part has the = sign in it also.
My code doesn't work as it was assuming the value part doesnt' have an = sign in it, and it isn't using regex simply String.Split('=').
Can someone help with the regex required, I added double quotes around both the key/value to help keep things seperate.
I didn't use a regex, but you could do something like the following:
string test =#"""key1""=""value1 http://www.example.com?a=1"";""key2""=""value2 http://www.example.com?a=2""";
string[] arr = test.Split(';');
foreach (string s in arr)
{
int index = s.IndexOf('=');
string key = s.Substring(0, index);
string value = s.Substring(index+1, s.Length - index);
}
Use the String.Split(char[], int) overload (http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx). The second parameter will limit the number of substrings to return. If you know your strings will always have at least 1 equal sign (key/value pairs), then set the second parameter to 2.
string x = "key1=value1 http://www.example.com?a=1;key2=value2 http://www.example.com?a=2;";
char[] equal = new char[1] { '=' };
char[] semi = new char[1] { ';' };
string[] list = x.Split(semi, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in list)
{
string[] kvp = s.Split(equal, 2);
Console.WriteLine("Key: {0}, Value: {1}", kvp[0], kvp[1]);
}
-
Result:
Key: key1, Value: value1 http://www.example.com?a=1
Key: key2, Value: value2 http://www.example.com?a=2
Well what you can do, is you can use IndexOf to get the index of the first =
int i = myStr.IndexOf('=');
and then you can use the String.Substring to get the key and value
string key = myStr.Substring(0, i)
string value = myStr.SubString(i+1);
Here is some documentation on the String Class that you might find useful
You need to match not split the text
var keys= Regex.Matches(yourString,"""(.*?)""=.*?(http.*?)"";").Cast<Match>().Select(x=>
new
{
key=x.Groups[1].Value,
value=x.Groups[2].Value
}
);
foreach(key in keys)
{
key.key;//the key value
key.value;//the value
}
Your regex should look like this.
"(.+?)"="(.+?)"
Sadly I do not know C# but this should work in every language. To get the results you have to select for every match:
group(1) as keys
group(2) as values
You could also try using the Split method with multiple tokens
here this will give you a string[] of multiple values that were split out based on your tokens
if you want to remove empty Entries you could also do the code like this
string strValue = #"""key1""=""value1 http://www.example.com?a=1"";""key2""=""value2 http://www.example.com?a=2""";
string[] strSplit = strValue.Split(new string[] { "\";\"", "\"=\"", "\"" }, StringSplitOptions.RemoveEmptyEntries);
Results
strSplit {string[4]} string[]
[0] "key1"
[1] "value1 http://www.example.com?a=1"
[2] "key2"
[3] "value2 http://www.example.com?a=2"
Use String.Split with StringSplitOptions.RemoveEmptyEntries and an array of strings with delimiters
string s = "\"key1\"=\"value1 http://www.example.com?a=1\";\"key2\"=\"value2 http://www.example.com?a=2\"";
string[] result = s.Split(new string[] { "\";\"", "\"=\"", "\"" },
StringSplitOptions.RemoveEmptyEntries);
result = {string[4]}
[0]: "key1"
[1]: "value1 http://www.example.com?a=1"
[2]: "key2"
[3]: "value2 http://www.example.com?a=2"
I use the following delimiters (including the double quotes):
";"
"="
"

ASP.NET C# String.Split

I want to split a string if there is a space between words.
For example:
"Blood Doner Jack Stv 240 o+"
When I split it using a single space it returns an array object with 6 items, but if I try it with the same set of text and there are 2 spaces in place of one it increase the array to 7:
"Blood Doner Jack Stv 240 o+"
So I want to know how to remove split it with a double space as well as a single.
I know I can use Replace() with 2 spaces to 1 space but what if I have 3 or 4 spaces?
Thanks in advance!
You can use the overload of String.Split which takes a StringSplitOptions:
string[] bits = text.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
Note that to avoid creating a char array on each call, you could use:
private static readonly char[] SplitSeparators = {' '};
...
string[] bits = text.Split(SplitSeparators,
StringSplitOptions.RemoveEmptyEntries);
just use StringSplitOptions.RemoveEmptyEntries:
var s = "Blood Doner Jack Stv 240 o+";
var arr = s.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);
Or you can replace many spaces with one using Regexp, and than Split:
string str = System.Text.RegularExpressions.RegEx.Replace(s ,#"\s+"," ");
var arr = str.Split(new[] {" "}, StringSplitOptions.None);
This will remove spaces:
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(#"[ ]{2,}", options);
tempo = regex.Replace(tempo, #" ");
Then you can split normally
How do I replace multiple spaces with a single space in C#?
How to remove extra space between two words using C#?
string s1 = "Blood Doner Jack Stv 240 o+";
Regex r = new Regex(#"\s+");
string s2 = r.Replace(s1, #" ");
string[] s3 = s2.Split(' ');

Perform Trim() while using Split()

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);

Categories