我知道可以将字符串附加在一起,但我想要能够在字符串中的每5个字符后添加一个特定的字符。
从这个 string alpha = abcdefghijklmnopqrstuvwxyz
到这个 string alpha = abcde-fghij-klmno-pqrst-uvwxy-z
我知道可以将字符串附加在一起,但我想要能够在字符串中的每5个字符后添加一个特定的字符。
从这个 string alpha = abcdefghijklmnopqrstuvwxyz
到这个 string alpha = abcde-fghij-klmno-pqrst-uvwxy-z
请记住,字符串是不可变的,因此您需要创建一个新字符串。
字符串是可枚举的,因此您可以在其上运行for循环。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string alpha = "abcdefghijklmnopqrstuvwxyz";
var builder = new StringBuilder();
int count = 0;
foreach (var c in alpha)
{
builder.Append(c);
if ((++count % 5) == 0)
{
builder.Append('-');
}
}
Console.WriteLine("Before: {0}", alpha);
alpha = builder.ToString();
Console.WriteLine("After: {0}", alpha);
}
}
}
生成以下内容:
Before: abcdefghijklmnopqrstuvwxyz
After: abcde-fghij-klmno-pqrst-uvwxy-z
我曾经遇到过类似的问题,需要将一串数字转换为时间段,通过添加:
和.
来实现。基本上,我需要将 235959999 转换为 23:59:59.999。对我来说很容易,因为我知道在哪里需要“插入”这些字符。
ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");
基本上是将ts重新赋值为带有插入字符的自身。我从后往前逐步进行操作,因为我懒得计算其他插入字符所需的额外数学运算。
您可以尝试类似的操作:
alpha = alpha.Insert(5,"-");
alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
...
这是我的解决方案,没有过度处理。
private static string AppendAtPosition(string baseString, int position, string character)
{
var sb = new StringBuilder(baseString);
for (int i = position; i < sb.Length; i += (position + character.Length))
sb.Insert(i, character);
return sb.ToString();
}
Console.WriteLine(AppendAtPosition("abcdefghijklmnopqrstuvwxyz", 5, "-"));
i += position
是错误的。不是吗? - Kobii +=(position + character.Length)
,因为插入character
字符串会使字符串中的索引发生偏移。 - Thibault Falisestring alpha = "abcdefghijklmnopqrstuvwxyz";
string newAlpha = "";
for (int i = 5; i < alpha.Length; i += 6)
{
newAlpha = alpha.Insert(i, "-");
alpha = newAlpha;
}
public string BreakEmailId(string emailId) {
string returnVal = string.Empty;
if (emailId.Length > 8) {
for (int i = 0; i < emailId.Length; i += 8) {
returnVal += emailId.Substring(i, 8) + " ";
}
}
return returnVal;
}
string[] lines = Regex.Split(value, ".{5}");
string out = "";
foreach (string line in lines)
{
out += "-" + line;
}
out = out.Substring(1);
Regex.Replace
或 String.Join
,而为什么要使用 \d
? - Kobipublic static class StringExtenstions
{
public static string InsertCharAtDividedPosition(this string str, int count, string character)
{
var i = 0;
while (++i * count + (i - 1) < str.Length)
{
str = str.Insert((i * count + (i - 1)), character);
}
return str;
}
}
并像这样使用:
var str = "abcdefghijklmnopqrstuvwxyz";
str = str.InsertCharAtDividedPosition(5, "-");
你可以使用这个:
string alpha = "abcdefghijklmnopqrstuvwxyz";
int length = alpha.Length;
for (int i = length - ((length - 1) % 5 + 1); i > 0; i -= 5)
{
alpha = alpha.Insert(i, "-");
}
适用于任何字符串。一如既往,大小并不重要。 ;)