我的编译器中有一个基本上看起来像这样的字符串:
\n $\n22\n95\n\n
我想将其格式化为一个字符串,如下所示:
22.95
这在C#中是否可行?特别是因为字符串中只有\ n而且我不确定如何过滤它?
答案 0 :(得分:2)
您可以通过以下方式执行此操作:
1)使用Split方法
将'\n'
字符串拆分
2)使用where和int.TryParse
过滤方法 3)然后使用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);
}
答案 2 :(得分: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.]", "");