简体   繁体   English

在C#中从双精度删除字符串

[英]Delete string from a double in C#

I am sending data from arduino to c# and have a problem. 我正在将数据从arduino发送到C#,并且有问题。 The value I get from the serialread comes with an "\\r" at the end of it, example: "19.42\\r". 我从serialread获取的值的末尾带有“ \\ r”,例如:“ 19.42 \\ r”。 I found a solution to delete the characters after my number by using Regex. 我找到了一种使用正则表达式删除号码后的字符的解决方案。 But it also makes my double an integer. 但这也使我的double成为整数。 "19.42\\r" becomes "1942". “ 19.42 \\ r”变为“ 1942”。 How can I delete my string but still keep the value as a double? 如何删除我的字符串,但仍将值保留为双精度值?

line = Regex.Replace(line, @"[^\\d]", string.Empty);

You want to trim the whitespace from the end of the string. 您要从字符串末尾修剪空白。

Use 采用

line = line.TrimEnd();

See the C# demo 参见C#演示

If you need to actually extract a double number from a string with regex, use 如果您实际上需要使用正则表达式从字符串中提取双精度数,请使用

var my_number = string.Empty;
var match = Regex.Match(line, @"[0-9]+\.[0-9]+");
if (match.Success) 
{   
    my_number = match.Value;
}

If the number can have no fractional part, use @"[0-9]*\\.?[0-9]+" regex. 如果数字不能有小数部分,请使用@"[0-9]*\\.?[0-9]+"正则表达式。

string data = "19.42\r";
return data.Substring(0, data.Length - 1);

or even better 甚至更好

data.TrimEnd('\r')

if \\r is fixed characters you want to remove 如果\\ r是您要删除的固定字符

string str = "awdawdaw\r";
str = str.replace("\r","");

if \\r is not fixed characters you want to remove 如果\\ r不是固定字符,则要删除

string str = "awdawdaw\\";
str = str.Substring((str.Length - 2), 2);  \\will be removed 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM