我有一個字符串,它基本上看起來像這樣在我的編譯器:C#reformating串入讀值使用正則表達式或其他方法
\n $\n22\n95\n\n
我想它格式化爲一個字符串,它看起來像如下:
22.95
這是可以在C#中嗎?特別是因爲在字符串中只有\ n,我不知道如何過濾它?
我有一個字符串,它基本上看起來像這樣在我的編譯器:C#reformating串入讀值使用正則表達式或其他方法
\n $\n22\n95\n\n
我想它格式化爲一個字符串,它看起來像如下:
22.95
這是可以在C#中嗎?特別是因爲在字符串中只有\ n,我不知道如何過濾它?
你能做到這一點的方式如下:
1)使用Split方法
2)使用where和int.TryParse篩選方法
3)再結合生成的拆分通過'\n'
字符串收集到一個字符串使用String.Join與"."
作爲分隔符
請試試這個算法, ñ發佈你的嘗試,我會給你全部的代碼。用linq只有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);
}
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.]", "");