如何从我传递的字符串中获取所有int值,如字符串str =" 1,2,3-8,9"到另一个字符串1,2,3,4,5,6,7,8,9 [英] 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

查看:76
本文介绍了如何从我传递的字符串中获取所有int值,如字符串str =" 1,2,3-8,9"到另一个字符串1,2,3,4,5,6,7,8,9的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从我传递的字符串中获取所有int值,例如



string str =1,2,3-8,9到另一个字符串1,2,3,4,5,6,7,8,9



我尝试过:



string str =1,2,3-8,9;

i需要将上面的字符串形成为

string st =1,2,3,4,5,6,7,8,9

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"

推荐答案

首先拆分字符串:

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



然后,您可以设置List< int>将数字转移到。

遍历每个子字符串,并检查它是否包含' - ' - string.Contains是你的朋友。

如果不是,使用int.TryParse将字符串转换为整数,并将其传递,添加到列表中。

如果它确实包含连字符,再次使用Split将其分开,将两个数字转换为整数,并使用Enumerable.Range将其转换为一系列值。您可以使用List.AddRange直接添加它们。


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.


我这样做了:

I have done that this way:
//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);





结果:最终字符串:'1,3,4,5,6,7 ,8,9,10,12,13,14,15,16,17,18,19,20,21,30'



我使用Linq查询解决了它。请阅读代码中的注释。



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.


生成平面整数序列的另一种方法:
Yet another way to produce the flat sequence of integers:
// 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);

EG在循环或 string.Join(...)中使用它:

E.g. use it in a loop or in a string.Join(...):

Console.WriteLine(string.Join(",", query));

干杯

Andi

Cheers
Andi


这篇关于如何从我传递的字符串中获取所有int值,如字符串str =&quot; 1,2,3-8,9&quot;到另一个字符串1,2,3,4,5,6,7,8,9的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆