0

長さが1000の文字列があります。それを分割して、別のコントロールに割り当てる必要があります。文字区切りはありません。
コントロールに割り当てている各文字列には同じ長さが含まれていないためです。今のところ、長さを指定している部分文字列を使用してそれを行っています。しかし、長さが大きいので、私にとっては多忙になっています。

より簡単な方法で分割して割り当てる方法はありますか?

4

2 に答える 2

2

この文字列コンストラクタを使用できます:

 var input = "Some 1000 character long string ...";
 var inputChars = input.ToCharArray();

 control1.Value = new string(inputChars, 0, 100);   // chars 0-100 of input
 control2.Value = new string(inputChars, 100, 20);  // chars 100-120 of input
 control3.Value = new string(inputChars, 120, 50);  // chars 120-170 of input
 ...

または使用Substring

 var input = "Some 1000 character long string ...";

 control1.Value = input.Substring(0, 100);   // chars 0-100 of input
 control2.Value = input.Substring(100, 20);  // chars 100-120 of input
 control3.Value = input.Substring(120, 50);  // chars 120-170 of input

これを行うこともできます

var parts = new [] 
{
     Tuple.Create(0, 100),
     Tuple.Create(100, 20),
     Tuple.Create(120, 50),
}

var inputParts = parts.Select(p => input.Substring(p.Item1, p.Item2))
                      .ToArray();
control1.Value = inputParts[0];
control2.Value = inputParts[1];
control3.Value = inputParts[3];

これにより、コントロールの数が増えるにつれて、保守がはるかに簡単になります。この「パーツ」のリストは静的に保存できるため、コードを複製することなく、アプリケーションの他の場所で再利用できます。

すべてのコントロールが同じタイプの場合、これを行うことができます:

 var parts = new [] 
 {
     new { control = control1, offset = 0, length = 100 },
     new { control = control2, offset = 100, length = 20 },
     new { control = control3, offset = 120, length = 50 },
 }

 foreach(var part in parts)
 {
     part.control.Value = new string(inputChars, part.offset, offset.length);
     // or part.control.Value = input.Substring(part.offset, offset.length);
 }
于 2013-07-15T12:15:27.980 に答える