简体   繁体   English

如何在常规字符串上打印.NET String.Format空格字符?

[英]How to print .NET String.Format space character on a regular string?

I am working on strings in .Net Core. 我正在研究.Net Core中的字符串。 I have a string formatted using :n and when it is formatted the output is 123 456,00 . 我有一个使用:n格式化的字符串,当它被格式化时,输出是123 456,00 I wanted to assert that the formatted string is equal to the string i wish it to be but i get an Assert.Equal Failure() and the problem is in the space character. 我想声明格式化的字符串等于我希望它的字符串,但我得到一个Assert.Equal Failure() ,问题出在空格字符中。 In the output it asserts that the two spaces are different. 在输出中,它断言两个空格是不同的。

Here is my code : 这是我的代码:

public void Separator()
{
    var str = string.Format("{0:n}", 123456);
    Assert.Equal("123 456,00",str);
}

I also compared the space character from the formatted string to a regular space character with an assert as follows Assert.Equal(' ',str[3]); 我还将格式化字符串中的空格字符与带有断言的常规空格字符进行比较,如下所示: Assert.Equal(' ',str[3]); i get that the expected value is 0x00a . 我得到的预期值是0x00a

Why is this happening and how can i get the same character without using string.Format() ? 为什么会发生这种情况,如何在不使用string.Format()情况下获得相同的字符?

The culture you are using specifies that the number group separator is a different ASCII character than space. 您正在使用的文化指定数字组分隔符是与空格不同的ASCII字符。 I'm guessing you are using ru-RU here, which means the digit is ASCII character 160, which means those strings will not match if you have just typed a space. 我猜你在这里使用ru-RU ,这意味着数字是ASCII字符160,这意味着如果你刚输入一个空格,那些字符串将不匹配。

You could replace the space with the culture's separator like this for example: 您可以使用文化的分隔符替换空格,例如:

var currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
var stringToCompare = "123 456,00".Replace(
    " ", 
    currentCulture.NumberFormat.NumberGroupSeparator);

Assert.Equal(stringToCompare, str);

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

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