C#问题,需要帮助!? [英] C# Question, need help!?

查看:53
本文介绍了C#问题,需要帮助!?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图分割一个数字字符串,用逗号分隔,用Pipes代替。还有一些数字在范围内,我想列出所有数字。例子:

这是我的桌子:



OLD COLUMN ------------- NEW COLUMN

原始列------------我希望它改为

(1,3-6,8)-------- ------------(1 | 3 | 4 | 5 | 6 | 8)

(3,5,9,11-13,15,17) - -------(3 | 5 | 9 | 11 | 12 | 13 | 15 | 17)



请帮助,我正在努力解决问题。 />


我最大的问题是如何获得范围内的数字。例如:3-6,表示3,4,5,6。如何使用之间的所有数字循环或替换短划线?在用管道替换昏迷之前?

解决方案

试试这个:



在设计时:



1.在表格上放一个Button,'button1

2.将两个TextBox,'textBox1,'textBox2放在同一个表格上

3.将下面的代码写入Form的.cs文件

4. wire-up'button1的Click事件处理程序为'button1_Click如下所示



在运行时:



1.将测试文本输入'textBox1,点击'button1

2.检查'textBox2中的输出



代码:

  private  StringBuilder sb =  new  StringBuilder(); 
private string [] stringAry;
private string [] seriesStringAry;
private int iStart;
private int iEnd;

private void button1_Click( object sender,EventArgs e)
{
sb.Clear();

stringAry = textBox1.Text.Split(' ,');

foreach string theString in stringAry)
{
// 消除任何空白
theString.Trim();

// 检查系列
if (theString.Contains( - ))
{
seriesStringAry = theString.Split(' - ');

// 防范坏的子字符串数据
< span class =code-keyword> if (seriesStringAry.Length!= 2 throw new InvalidDataException( 源中格式错误的子字符串字符串);

iStart = Convert.ToInt32(seriesStringAry [ 0 ]);
iEnd = Convert.ToInt32(seriesStringAry [ 1 ]);

for int i = iStart; i < = iEnd; i ++)
{
sb.Append(i.ToString());
sb.Append( |);
}
}
else
{
sb.Append(theString);
sb.Append( |);
}
}

// 敲掉最后的|
sb.Remove(sb.Length - 1 1 );

textBox2.Text = sb.ToString();
}

讨论:这会有效,但不会感觉优雅代码:)



注意这个想法假设总是有一个|这里的角色,敲掉它,是一种邋 - 的清理方式。对于生产代码,我(我认为你)应该首先:在敲掉任何东西之前检查是否有最终的|。其次,您可以重新编写代码以使用for循环来代替foreach,在这种情况下,您可以跟踪何时到达处理的最终输出,并且在那时,省略写|字符。我只是在这里懒惰,对不起。



如果你想要解析的文本中的条目是这样的形式会发生什么:15-11 ?在这种情况下,这里的代码会失败,但重新编写代码以处理这种情况并不困难。



另请注意,这里的假设是:你解析的数据中的字符串总是代表整数。



现在,真正优雅的将是请参阅CP的RegEx专家之一,仅使用RegEx添加此问题的答案!


Hi
在下面的代码示例中,我正在使用正则表达式引擎

从输入字符串中检索目标数字到min&最大组

从那里创建输出字符串的简单循环。



  string  r =   3,5,9,11-13,15,17 ; 

StringBuilder sb = new StringBuilder();
MatchCollection匹配=
Regex.Matches(r, (?:(?< min> (?: - (小于MAX> [0-9] +); [0-9] +)?)));

foreach (匹配匹配 匹配)
{
sb.Append(match.Groups [ min]。Value);
sb.Append( |);

if (!string.IsNullOrWhiteSpace(match.Groups [ max]。值))
{
int max = int .Parse(match.Groups [ max]。值);
for int i = int .Parse(match.Groups [ min]。值)+ 1 ; i < = max; i ++)
{
sb.Append(i);
sb.Append( |);
}
}
}
sb.Remove(sb.Length - 1 1 );


试试这个:

 string [] newString = oldString.Split(','); 





newString数组将所有项目分开,您可以连接各个值。







这样做:

 string newString = oldString.Replace(,,|); 





这只会用垂直管道替换逗号。


I am try to split a strings of numbers which is separated by commas to be replaced by Pipes. Also some of numbers are in range and I want to list all the numbers. EXAMPLE:
This is my table:

OLD COLUMN-------------NEW COLUMN
Original Column------------I want it change to
(1,3-6,8)--------------------(1|3|4|5|6|8)
(3,5,9,11-13,15,17)---------(3|5|9|11|12|13|15|17)

Please help, am struggling with problem.

My biggest problem is how do I get the numbers in the range. Example where it says: 3-6, it means 3,4,5,6. How do i loop or or replace the dash with all the numbers between? before replace the comas with the pipe?

解决方案

Try this:

At design-time:

1. put a Button, 'button1 on a Form
2. put two TextBoxes, 'textBox1, 'textBox2 on the same Form
3. psste the code below into the Form's .cs file
4. wire-up 'button1's Click Event Handler to 'button1_Click shown below

At run-time:

1. enter your test text into 'textBox1, click 'button1
2. examine the output in 'textBox2

The code:

private StringBuilder sb = new StringBuilder();
private string[] stringAry;
private string[] seriesStringAry;
private int iStart;
private int iEnd;

private void button1_Click(object sender, EventArgs e)
{
    sb.Clear();

    stringAry = textBox1.Text.Split(',');

    foreach (string theString in stringAry)
    {
        // eliminate any white-space
        theString.Trim();

        // check for a series
        if (theString.Contains("-"))
        {
            seriesStringAry = theString.Split('-');

            // guard against bad sub-string data
            if (seriesStringAry.Length != 2) throw new InvalidDataException("malformed sub-string in your source string");

            iStart = Convert.ToInt32(seriesStringAry[0]);
            iEnd = Convert.ToInt32(seriesStringAry[1]);

            for (int i = iStart; i <= iEnd; i++)
            {
                sb.Append(i.ToString());
                sb.Append("|");
            }
        }
        else
        {
            sb.Append(theString);
            sb.Append("|");
        }
    }

    // knock off the final "|"
    sb.Remove(sb.Length - 1, 1);

    textBox2.Text = sb.ToString();
}

Discussion: This will work, but doesn't "feel like" elegant code :)

Note that the idea of assuming there is always a final "|" character here, and "knocking it off," is kind of a sloppy way of cleaning-up-after. For "production code," I (and I think you) should first: check there is a final "|," before knocking anything off. And, second, you can re-write the code to use a for-loop for the main loop, instead of foreach, in which case you can keep track of when you reach the final output of your processing, and, at that point, omit writing the "|" character. I was just lazy here, sorry.

What would happen if you wanted an entry in the text you were parsing to be in a form like this: "15-11" ? The code here would fail, in that case, but it would not be that difficult to re-write the code to handle that case.

Note, also, that the assumption here is: the strings in the data you parse always represent integers.

Now, what would be really "elegant" would be to see one of CP's RegEx experts add an answer to this question using only RegEx !


Hi In the following code example I am using the regular expression engine in order
to retrieve the target numbers from the input string into the min & max groups
from there its a simple loop creating the output string.

string r = "3,5,9,11-13,15,17";

StringBuilder sb = new StringBuilder();
MatchCollection matches = 
                Regex.Matches(r, "(?:(?<min>[0-9]+)(?:-(?<max>[0-9]+))?)");

foreach (Match match in matches)
{
   sb.Append(match.Groups["min"].Value);
   sb.Append("|");
     
   if (!string.IsNullOrWhiteSpace(match.Groups["max"].Value))
   {
      int max = int.Parse(match.Groups["max"].Value);
      for (int i = int.Parse(match.Groups["min"].Value) + 1; i <= max; i++)
      {
         sb.Append(i);
         sb.Append("|");                
      }
   }
}
sb.Remove(sb.Length - 1, 1);


Try this:

string[] newString = oldString.Split(',');



The "newString" array will have all the items separated and you can concatenate the individual values.

or

do this:

string newString = oldString.Replace(",","|");



This will just replace the commas with vertical pipes.


这篇关于C#问题,需要帮助!?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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