简体   繁体   English

使用string.format将空格插入到字符串中

[英]Insert spaces into string using string.format

I've been using C# String.Format for formatting numbers before like this (in this example I simply want to insert a space): 我一直在使用C#String.Format格式化数字之前(在这个例子中我只是想插入一个空格):

String.Format("{0:### ###}", 123456);

output: 输出:

"123 456"

In this particular case, the number is a string. 在这种特殊情况下,数字是一个字符串。 My first thought was to simply parse it to a number, but it makes no sense in the context, and there must be a prettier way. 我的第一个想法是简单地将它解析为一个数字,但在上下文中没有任何意义,并且必须有一个更漂亮的方式。

Following does not work, as ## looks for numbers 以下不起作用,因为##查找数字

String.Format("{0:### ###}", "123456");

output: 输出:

"123456"

What is the string equivalent to # when formatting? 格式化时,#等效于什么字符串? The awesomeness of String.Format is still fairly new to me. String.Format的真棒对我来说还是比较新的。

You have to parse the string to a number first. 您必须先将字符串解析为数字。

int number = int.Parse("123456");
String.Format("{0:### ###}", number);

of course you could also use string methods but that's not as reliable and less safe: 当然你也可以使用字符串方法,但那不可靠且不太安全:

string strNumber =  "123456";
String.Format("{0} {1}", strNumber.Remove(3), strNumber.Substring(3));

As Heinzi pointed out, you can not have format specifier for string arguments. 正如Heinzi指出的那样,你不能拥有字符串参数的格式说明符。

So, instead of String.Format, you may use following: 因此,您可以使用以下代码:而不是String.Format:

string myNum="123456";
myNum=myNum.Insert(3," ");

Not very beautiful, and the extra work might outweigh the gains, but if the input is a string on that format, you could do: 不是很漂亮,额外的工作可能会超过收益,但如果输入是该格式的字符串,你可以这样做:

var str = "123456";
var result = String.Format("{0} {1}", str.Substring(0,3), str.Substring(3));

string is not a IFormattable string不是IFormattable

Console.WriteLine("123456" is IFormattable); // False
Console.WriteLine(21321 is IFormattable); // True

No point to supply a format if the argument is not IFormattable only way is to convert your string to int or long 如果参数不是IFormattable则无需提供格式,只有将字符串转换为intlong

There is no way to do what you want unless you parse the string first. 除非先解析字符串,否则无法按照自己的意愿行事。

Based on your comments, you only really need a simple formatting so you are better off just implementing a small helper method and thats it. 根据您的评论,您只需要一个简单的格式,这样您最好只是实现一个小帮助方法就可以了。 (IMHO it's not really a good idea to parse the string if it isn't logically a number; you can't really be sure that in the future the input string might not be a number at all. (恕我直言,如果它不是逻辑上的数字,解析字符串并不是一个好主意;你不能确定将来输入字符串可能根本不是数字。

I'd go for something similar to: 我会去寻找类似的东西:

 public static string Group(this string s, int groupSize = 3, char groupSeparator = ' ')
 {
     var formattedIdentifierBuilder = new StringBuilder();

     for (int i = 0; i < s.Length; i++)
     {
         if (i != 0 && (s.Length - i) % groupSize == 0)
         {
             formattedIdentifierBuilder.Append(groupSeparator);
         }

         formattedIdentifierBuilder.Append(s[i]);
     }

     return formattedIdentifierBuilder.ToString();
 }

EDIT : Generalized to generic grouping size and group separator. 编辑 :通用分组大小和组分隔符。

We're doing string manipulation, so we could always use a regex. 我们正在进行字符串操作,所以我们总是可以使用正则表达式。

Adapted slightly from here : 这里略微改编:

class MyClass
{
   static void Main(string[] args)
   {
      string sInput, sRegex;

      // The string to search.
      sInput = "123456789";

      // The regular expression.
      sRegex = "[0-9][0-9][0-9]";

      Regex r = new Regex(sRegex);

      MyClass c = new MyClass();

      // Assign the replace method to the MatchEvaluator delegate.
      MatchEvaluator myEvaluator = new MatchEvaluator(c.ReplaceNums);

      // Replace matched characters using the delegate method.
      sInput = r.Replace(sInput, myEvaluator);

      // Write out the modified string.
      Console.WriteLine(sInput);
   }

   public string ReplaceNums(Match m)
   // Replace each Regex match with match + " "
   {
      return m.ToString()+" ";
   }

}

How's that? 怎么样?

It's been ages since I used C# and I can't test, but this may work as a one-liner which may be "neater" if you only need it once: 我使用C#已经很久了,我无法测试,但如果您只需要一次,这可能会作为一个单线程,可能会“整洁”:

sInput = Regex("[0-9][0-9][0-9]").Replace(sInput,MatchEvaluator(Match m => m.ToString()+" "));

The problem is that # is a Digit placeholder and it is specific to numeric formatting only . 问题是#是一个Digit占位符 ,它仅适用数字格式 Hence, you can't use this on strings. 因此,您不能在字符串上使用它。

Either parse the string to a numeric, so the formatting rules apply, or use other methods to split the string in two. 将字符串解析为数字,因此应用格式规则,或使用其他方法将字符串拆分为两个。

string.Format("{0:### ###}", int.Parse("123456"));

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

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