2013-05-19 49 views

回答

0

试试这个代码,设置input值并获得output

var input = "D1-D5"; 
string output = string.Empty; 
if (input.IndexOf("-") > 0) 
{ 
    var values = input.Split('-'); 
    int first = int.Parse(System.Text.RegularExpressions.Regex.Match(values[0], @"\d+").Value); 
    int second = int.Parse(System.Text.RegularExpressions.Regex.Match(values[1], @"\d+").Value); 

    for (int i = first; i <= second; i++) 
    { 
     output += "D" + i + ","; 
    } 
    output = output.Remove(output.Length - 1); 
} 
0

错误检查为每个域的要求是你。 此代码假定输入正确并适用于您提供的示例。

夫妇笔记:

  1. "" + ...级联和空字符串是克服简单的情况下
  2. 您需要检查输入的字符串是正确的类型转换问题的简单方法。
  3. 代码可以扩展到多个范围。目前,如果您提供DxDx-Dy以外的其他东西,则会打印出“错误”。你可以为此使用递归函数。

    private static string getString(string input, char controlChar='D') 
    { 
        string numbersOnly = input.Replace("" + controlChar, ""); 
    
        string[] bounds = numbersOnly.Split('-'); 
    
        if(bounds.Length == 1) 
        { 
         return "" + controlChar + bounds[0]; 
        } 
        else if (bounds.Length == 2) 
        { 
         string str = ""; 
         for (int i = Int32.Parse(bounds[0]); i <= Int32.Parse(bounds[1]); i++) 
         { 
          str += controlChar + "" + i + ","; 
         } 
    
         str = str.TrimEnd(','); 
    
         return str; 
        } 
        else 
        { 
         return "Error"; 
        } 
    } 
    
0
//To find a middle string inclusively 
    var alpha = "abcdefghijklmnopqrstuvwxyz"; 

    var begin = "cde"; 
    var end = "mno"; 

    var beginIndex = alpha.IndexOf(begin); 
    var endIndex = alpha.IndexOf(end); 

    if (beginIndex != -1 && endIndex != -1) 
    { 
    var middle = alpha.Substring(beginIndex, endIndex + end.Length - beginIndex); 
    System.Diagnostics.Debugger.Break(); 
    } 
0

您可以使用此代码尝试:

private static string GetString(string inputStr, char replaceChar) 
{ 
    string outputStr = string.Empty; 

    var strColl = inputStr.Replace(replaceChar, ' ').Split('-'); 
    int min = Convert.ToInt32(strColl[0]); 
    int max = min; 

    if (strColl.Count() > 1) max = Convert.ToInt32(strColl[1]); 

    for(int i = min; i <= max; i++) 
    { 
     outputStr += "D" + i + ","; 
    } 

    return outputStr = outputStr.TrimEnd(','); // remove the last comma (,) 
} 

你可以简单的调用这个方法如下:

GetString("D1-D3", 'D'); 
相关问题