2017-09-04 26 views

回答

2

你能做到這一點的方式如下:

1)使用Split方法

2)使用whereint.TryParse篩選方法

3)再結合生成的拆分通過'\n'字符串收集到一個字符串使用String.Join"."作爲分隔符

請試試這個算法, ñ發佈你的嘗試,我會給你全部的代碼。用linq只有1行代碼。請給我留言,如果你在路上

1

這裏的困難是一個簡單的實施Mong Zhu's answer

private static string StringDouble(string input) 
{ 
    var intSplitResult = 
     input.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries) 
       .Select(str => 
       { 
        int value; 
        bool success = int.TryParse(str, out value); 
        return new { value, success }; 
       }) 
       .Where(pair => pair.success) 
       .Select(pair => pair.value); 

    if (intSplitResult.Count() != 2) 
    { 
     throw new ArgumentException(
        $"Invalid Input: [{input}]. Do not contains the right number of number!" 
        , nameof(input)); 
    } 

    return string.Join(".", intSplitResult); 
} 
1
in two steps using first positive look behind and positive look ahead  
    then replacing non digit and non dot. 

      var text = "\n $\n22\n95\n\" 

      var pattern = @"((?<=\d+))(\n)((?=\d+))"; 

      var st = Regex.Replace(text, pattern, @"$1.$3") 

      st = Regex.Replace(st, @"[^\d.]", ""); 
相關問題