C# 在字符串中的几个字符后添加空格
我想在字符串(数组中的字符串)中的 2 个字符后添加空格,例如: 1234567890
应该是 12 34 56 78 90
,有什么建议如何做到这一点吗?
I wanna add space in string( string from array) after 2 characters, for example:1234567890
should be 12 34 56 78 90
, any suggestions how to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能必须执行这样的循环:
这可能会大量使用字符串,因此请确保您阅读了有效的字符串连接
You would probably have to do a loop as such:
This could be heavy on string usage, so make sure you read up on effective string concatenation
我建议执行以下步骤
创建一个将遍历输入字符串长度的 For 循环。
在每次运行 For 循环期间,将字符串的第 i 个元素连接到结果中,即
result+=input[i];
在 for 循环内部跟踪计数,并在每次
count%2 == 0
之后将空格连接到结果。result+=" ";
希望这有帮助。
I would recommend following steps
Create a For loop which will go through the length of input string.
During each run of For loop concat ith elemen of string in to the result i.e.
result+=input[i];
Inside for loop keep track of count and after every
count%2 == 0
concat space to the result.result+=" ";
Hope this helps.
如果您专门希望格式化固定数量的数字(例如上面的示例),那么以下内容将满足您的需求。
请注意,这假设您的
1234567890
存储为数字。如果n
的类型为string
,则不会格式化。您可以通过在格式化之前将n
转换为数字来解决此问题。如果您的字符数量不受限制,则需要更通用的解决方案。
If your looking specifically to format a fixed amount of numbers, such as the example above, the following will fit your needs.
Note, this assumes that your
1234567890
is stored as a number. It will not format ifn
is of typestring
. You can overcome this by castingn
to a number prior to formatting.If you have an unbounded number of characters, you'll need a more versitile solution.