Dividir Cadeia de comprimento
Pergunta
Eu tenho um valor de cadeia que seu comprimento é de 5000 + caracteres, eu quero dividir isso em 76 caracteres de comprimento, com uma nova linha no final de cada 76 caracteres. Como eu woudld fazer isso em c #?
Solução
Se você estiver escrevendo dados Base64, tente escrever
Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
Isto irá inserir uma nova linha a cada 76 caracteres
Outras dicas
Um lado sobre isso, se você quiser StringBuilder versus desempenho seqüência o melhor artigo é o codeproject encontrados aqui .
(Isto não mostra o tamanho corda no entanto)
Em poucas palavras, StringBuilder não é mais rápido até que um limite for atingido com o comprimento da corda (ou contactenation repetida), o que você está bem abaixo, de modo a manter a concatenação regular e métodos de String.
Tente isto:
s = Regex.Replace(s, @"(?<=\G.{76})", "\r\n");
EDIT: Aparentemente, este é o método mais lento de todos aqueles postado até agora. Eu me pergunto como ele se você pré-compilar o regex:
Regex rx0 = new Regex(@"(?<=\G.{76})");
s = rx0.Replace(s, "\r\n"); // only time this portion
Além disso, como ele se compara a uma abordagem de correspondência em linha reta?
Regex rx1 = new Regex(".{76}");
s = rx1.Replace(s, "$0\r\n"); // only time this portion
Eu sempre me perguntei o quão caro essas visões traseiras ilimitados são.
Um pouco mais feio ... mas muito mais rápido;) (esta versão levou 161 carrapatos ... Aric do tomou 413)
Eu postei meu código de teste no meu blog. http://hackersbasement.com/?p=134 (Eu também achei StringBuilder ser muito mais lento do que String.Join)
http://hackersbasement.com/?p=139 <= resultados atualizados
string chopMe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Stopwatch sw = new Stopwatch();
sw.Start();
char[] chopMeArray = chopMe.ToCharArray();
int totalLength = chopMe.Length;
int partLength = 12;
int partCount = (totalLength / partLength) + ((totalLength % partLength == 0) ? 0 : 1);
int posIndex = 0;
char[] part = new char[partLength];
string[] parts = new string[partCount];
int get = partLength;
for (int i = 0; i < partCount; i++)
{
get = Math.Min(partLength, totalLength - posIndex);
Array.Copy(chopMeArray, posIndex, part, 0, get);
parts[i] = new string(part, 0, get);
posIndex += partLength;
}
var output = string.Join("\r\n", parts) + "\r\n";
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
public static string InsertNewLine(string s, int len)
{
StringBuilder sb = new StringBuilder(s.Length + (int)(s.Length/len) + 1);
int start = 0;
for (start=0; start<s.Length-len; start+=len)
{
sb.Append(s.Substring(start, len));
sb.Append(Environment.NewLine);
}
sb.Append(s.Substring(start));
return sb.ToString();
}
que s seria a sua cadeia de entrada e len o comprimento da linha desejada (76).
string[] FixedSplit(string s, int len)
{
List<string> output;
while (s.Length > len)
{
output.Add(s.Substring(0, len) + "\n");
s.Remove(0, len);
}
output.Add(s + "\n");
return output.ToArray();
}
public static IEnumerable<string> SplitString(string s, int length)
{
var buf = new char[length];
using (var rdr = new StringReader(s))
{
int l;
l = rdr.ReadBlock(buf, 0, length);
while (l > 0)
{
yield return (new string(buf, 0, l)) + Environment.NewLine;
l = rdr.ReadBlock(buf, 0, length);
}
}
}
Em seguida, colocá-los juntos novamente:
string theString = GetLongString();
StringBuilder buf = new StringBuilder(theString.Length + theString.Length/76);
foreach (string s in SplitString(theString, 76) { buf.Append(s); }
string result = buf.ToString();
Ou você poderia fazer isso:
string InsertNewLines(string s, int interval)
{
char[] buf = new char[s.Length + (int)Math.Ceiling(s.Length / (double)interval)];
using (var rdr = new StringReader(s))
{
for (int i=0; i<buf.Length-interval; i++)
{
rdr.ReadBlock(buf, i, interval);
i+=interval;
buf[i] = '\n';
}
if (i < s.Length)
{
rdr.ReadBlock(buf, i, s.Length - i);
buf[buf.Length - 1] = '\n';
}
}
return new string(buf);
}
Mais uma .... (primeira vez através slowish, execuções subseqüentes, similar aos tempos mais rápidos postadas acima)
private void button1_Click(object sender, EventArgs e)
{
string chopMe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Stopwatch sw = new Stopwatch();
sw.Start();
string result = string.Join("\r\n", ChopString(chopMe).ToArray());
sw.Stop();
MessageBox.Show(result + " " + sw.ToString());
}
public IEnumerable<string> ChopString(string s)
{
int i = 0;
while (i < s.Length)
{
yield return i + PARTLENGTH <= s.Length ? s.Substring(i,PARTLENGTH) :s.Substring(i) ;
i += PARTLENGTH;
}
}
Edit: Eu estava curioso para ver o quão rápido substring estava ...
A cadeia é de 5000 caracteres ... Eu não acho que a velocidade é realmente da essência, a menos que você está fazendo isso milhares ou talvez até milhões de vezes, especialmente quando o OP nem sequer mencionar a velocidade sendo importante. otimização prematura?
Eu provavelmente usar a recursividade como ele vai, na minha opinião, levar ao código mais simples.
Isto não pode ser syntatically correta, como eu sei .NET, mas não C #.
String ChunkString(String s, Integer chunkLength) {
if (s.Length <= chunkLength) return s;
return String.Concat(s.Substring(0, chunkLength),
ChunkString(s.Substring(chunkLength)));
}
principalmente para se divertir, aqui está uma solução diferente implementado como método de extensão para string: (\ R \ n explicitamente utilizada de modo que só suportam formato para nova linha);
public static string Split(this string str, int len)
{
char org = str.ToCharArray();
int parts = str.Length / len + (str.Length % len == 0 ? 0 : 1);
int stepSize = len + newline.Length;
char[] result = new char[parts * stepSize];
int resLen = result.Length;
for (int i =0;i<resLen ;i+stepSize)
{
Array.Copy(org,i*len,result,i*stepSize);
resLen[i++] = '\r';
resLen[i++] = '\n';
}
return new string(result);
}
No final, este seria o que eu usaria, acho
static string fredou()
{
string s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
int partLength = 12;
int stringLength = s.Length;
StringBuilder n = new StringBuilder(stringLength + (int)(stringLength / partLength) + 1);
int chopSize = 0;
int pos = 0;
while (pos < stringLength)
{
chopSize = (pos + partLength) < stringLength ? partLength : stringLength - pos;
n.Append(s , pos, chopSize);
n.Append("\r\n");
pos += chopSize;
}
return n.ToString();
}
olhando AppendLine sob refletor:
<ComVisible(False)> _
Public Function AppendLine(ByVal value As String) As StringBuilder
Me.Append(value)
Return Me.Append(Environment.NewLine)
End Function
Public Shared ReadOnly Property NewLine As String
Get
Return ChrW(13) & ChrW(10)
End Get
End Property
Para mim, a velocidade sábio, fazê-lo manualmente> AppendLine
Estou parcelamento da corda por 35
var tempstore ="12345678901234567890123456789012345";
for (int k = 0; k < tempstore.Length; k += 35)
{
PMSIMTRequest.Append(tempstore.Substring(k, tempstore.Length - k > 35 ? 35 : tempstore.Length - k));
PMSIMTRequest.Append(System.Environment.NewLine);
}
messagebox.Show(PMSIMTRequest.tostring());
@ resposta de M4N é muito bom, mas eu acho que while statement
é mais fácil de entender do que for statement
.
public static string InsertNewLine(string source, int len = 76)
{
var sb = new StringBuilder(source.Length + (int)(source.Length / len) + 1);
var start = 0;
while ((start + len) < source.Length)
{
sb.Append(source.Substring(start, len));
sb.Append(Environment.NewLine);
start += len;
}
sb.Append(source.Substring(start));
return sb.ToString();
}