我想要将一个长字符串分割成类似以下的样式:
"weygjjsgdgk"
"weygwjiewle"
"wegygciefew"
"jknfkeuwyfj"
"kdygwfsn"
每个子串长度为10个字符,同时用双引号包裹。请问如何实现?
"weygjjsgdgk"
"weygwjiewle"
"wegygciefew"
"jknfkeuwyfj"
"kdygwfsn"
每个子串长度为10个字符,同时用双引号包裹。请问如何实现?
正则表达式方法
string instr = "weygjjsgdgkweygwjiewlewegygciefewjknfkeuwyfjkdygwfsn";
string results = Regex.Replace(instr, "(.{1,11})", "\"$1\"\n");
Console.WriteLine(results);
结果
"weygjjsgdgk"
"weygwjiewle"
"wegygciefew"
"jknfkeuwyfj"
"kdygwfsn"
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "012345678901234567890";
int remaining = input.Length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.Length; i+=10)
{
sb.Append('"').Append(input.Substring(i, Math.Min(10, remaining))).Append('"');
remaining -= 10;
}
Console.WriteLine(sb.ToString());
}
}
}
private static string[] SplitBy(string source, int count)
{
const string Separator = "╩";
var byCount = source.Select((c, i) => i % count == 0 ? Separator + c : c.ToString()).ToArray();
var inString = string.Join(string.Empty, byCount);
return inString.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
}
var splitted = SplitBy("some very long str", 5);
结果:
some
very
long
str
您可以使用子字符串方法,Substring(int startIndex, int length)
和Substring(int startIndex)
。我几乎没有做过C#,但我认为它应该是这个样子:
string originalString = "weygjjsgdgkweygwjiewlewegygciefewjknfkeuwyfjkdygwfsn";
string newString = "";
while (originalString.Length > 10) {
string line = originalString.Substring(0, 10);
newString = "\"" + line + "\"\n";
originalString = originalString.Substring(10);
}
newString = "\"" + originalString + "\"\n";
string input = "...";
IEnumerable<string> output =
from i in Enumerable.Range(0, (input.Length + 1) / 10)
let start = i * 10
let length = Math.Min(10, input.Length - start)
select "\"" + input.Substring(start, length) + "\""
也许稍微更快的方法 - 对于较长的字符串应该更快。
static void Main(string[] args)
{
string input = "012345678901234567890";
// Create a StringBuilder with enough space
StringBuilder sb = new StringBuilder(input.Length + input.Length / 10 * 3 + 3);
sb.Append('"');
for (int n = 0; n < input.Length; n++)
{
// don't add if this is the first char
if (n > 0 && n % 10 == 0)
{
sb.Append("\"\n\"");
}
sb.Append(input[n]);
}
sb.Append('"');
Console.WriteLine(sb.ToString());
}
foreach(var text in "abcdefghijklmnopqrstuvwxyz".SplitString(5))
{
Debug.WriteLine(text);
}
public static IEnumerable<string> SplitString(this string input, int outputStringLength)
{
var count = 0;
while (count < input.Length)
{
var length = Math.Min(outputStringLength, input.Length - count);
yield return string.Format("\"{0}\"", input.Substring(count, length));
count += outputStringLength;
}
}