Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
2.67/5 (6 votes)
See more:
how to get the all int values from a string which i pass like

string str ="1,2,3-8,9" to an other string 1,2,3,4,5,6,7,8,9

What I have tried:

string str= "1,2,3-8,9";
i need the above string to be formed as
string st = "1,2,3,4,5,6,7,8,9"
Posted
Comments
Zoltán Zörgő 16-Feb-16 8:17am    
This is what you have tried? Really? Dude...
Do you know regualr expressions? It is quite easy with it.
Member 10902837 16-Feb-16 8:22am    
i need in the c# i'm trying it can u help if know how to do
Patrice T 16-Feb-16 8:34am    
You need to learn Regex
Member 10902837 16-Feb-16 8:38am    
thanks for that and i done with this
Richard MacCutchan 16-Feb-16 9:25am    
You just need to split your string into its separate parts and identify the different types: single digit and range value.

Start by splitting the string:
C#
string[] parts = "1,2,3-8,9".Split(',');

You can then set up a List<int> to transfer the digits into.
Loop through each substring, and check if it contains a '-' - string.Contains is your friend here.
If it doesn't, use int.TryParse to convert the string to an integer, and it it passes, add to your list.
If it does contain a hyphen, use Split again to separate it, convert the two numbers to integers, and use Enumerable.Range to convert it to a range of values. You can use the List.AddRange to add them directly.
 
Share this answer
 
I have done that this way:
C#
//input string
string str ="1,3-8,9,10,12-21,30";

//get ranges (digit-digit)
//split them into Tuples(<int>,<int>) to be able to generate digits from-to
//finally - convert it into Enumerable<int>
var ranges = str.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries)
			.Where(x=>x.Contains("-"))
			.Select(x=> Tuple.Create(Convert.ToInt32(x.Split(new char[]{'-'}, StringSplitOptions.RemoveEmptyEntries)[0]),
									Convert.ToInt32(x.Split(new char[]{'-'}, StringSplitOptions.RemoveEmptyEntries)[1])))
			.SelectMany(x=>Enumerable.Range(x.Item1, x.Item2-x.Item1+1));

//get digits 
//concat digit-ranges
//join digits into final string
var digits = string.Join(",", str.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries)
				.Where(x=>!x.Contains("-"))
				.Select(x=>Convert.ToInt32(x))
				.Concat(ranges)
				.OrderBy(x=>x)
				.ToArray());
				
Console.WriteLine("final string: '{0}'", digits);


Result: final string: '1,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20,21,30'

I solved it using Linq queries. Please, read comments in the code.
 
Share this answer
 
Comments
Andreas Gieriet 16-Feb-16 16:01pm    
My 5, Maciej!
I have a similar solution posted (#3) with Regex and SelectMany.
Cheers
Andi
Maciej Los 16-Feb-16 16:59pm    
Thank you, Andi.
Yet another way to produce the flat sequence of integers:
C#
// 1. get all digits-digits|digits
//    note: any other characters are treated as separators
// 2. make for digits-digits: start number and number of items,
//     and for        digits: start number and number of items = 1
// 3. employ select-many to concatenate the ranges from 2 above
// 4. order by increasing numbers
var query = (from m in Regex.Matches(input, @"(\d+)(?:\s*-\s*(\d+))?").Cast<Match>()
                let a = int.Parse(m.Groups[1].Value)
                let v = m.Groups[2].Value
                let b = string.IsNullOrEmpty(v) ? a : int.Parse(v)
                let n = Math.Abs(b - a) + 1
                select new { a, n }
            )
            .SelectMany(t=>Enumerable.Range(t.a, t.n))
            .OrderBy(i=>i);
E.g. use it in a loop or in a string.Join(...):
C#
Console.WriteLine(string.Join(",", query));
Cheers
Andi
 
Share this answer
 
Comments
Maciej Los 16-Feb-16 17:01pm    
Andi, your solution looks perfect!
+5
Andreas Gieriet 16-Feb-16 17:06pm    
Thanks for your 5!
Andi

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900