我们如何在每两个字符之间的字符串中创建空格? [英] How do we make space in string between each two characters ?
本文介绍了我们如何在每两个字符之间的字符串中创建空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们如何在每两个字符之间的字符串中创建空格?
如果我有字符串s =23hhppyyqq我想让它s =23 hh pp yy qq
How do we make space in string between each two characters ?
if I have string s ="23hhppyyqq" I want to make it s = "23 hh pp yy qq"
推荐答案
这可能帮助您 - 如何在单词之间添加空格无空间的字符串 [ ^ ]。
This might help you - How to add spaces between words in a spaceless strings[^].
简单:
Easy:
string inp = "23hhppyyqq";
bool addSpace = true;
StringBuilder sb = new StringBuilder((input.Length * 3) / 2);
foreach (char c in inp)
{
if (addSpace) sb.Append(' ');
sb.Append(c);
addSpace = !addSpace;
}
string outp = sb.ToString().Trim();
这应该做:
This should do:
string input = "23hhppyyqq";
string result;
int requiredSpaces = (input.Length - 1) / 2;
if (requiredSpaces < 1)
{
result = input;
}
else
{
int resultLength = input.Length + requiredSpaces;
StringBuilder sb = new StringBuilder(resultLength);
for (int i=0; i<input.length; i++)
{
sb.Append(input[i]);
if (i % 2 == 1)
{
sb.Append(' ');
}
}
result = sb.ToString();
}
编辑:格式化
edit: formatting
这篇关于我们如何在每两个字符之间的字符串中创建空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文