# 對字符串進行相同長度循環截取 -开发者知识库

```

#region

對字符串循環截取

///

<summary>

///

對字符串循環截取

///

</summary>

///

<param name="str">

被截取的字符串

</param>

///

<param name="Length">

截取的長度

</param>

///

<returns></returns>

private

string

[] CutString(

string

str,

int

Length) {

int

StrTotalLength

=

str.Length;

//

字符串的總長度

int

ArraySize

=

0

;

//

根據Length的長度截取的份數

//

被截取的字符串小於 截取的長度

if

(StrTotalLength

<

Length) { MessageBox.Show(

"

字符串的總長度小於要截取的長度，非法操作！

"

);

return

null

;

//

ArraySize = (StrTotalLength / Length);

}

else

{

//

被截取的字符串的長度正好是整數倍

if

(StrTotalLength

%

Length

==

0

) { ArraySize

=

(StrTotalLength

/

Length);

string

[] a

=

new

string

[ArraySize];

for

(

int

i

=

0

; i

<

ArraySize; i

) { a[i]

=

str.Substring(i

*

Length, Length); }

return

a; }

else

{

try

{

//

加1快數組空間

ArraySize

=

(StrTotalLength

/

Length)

1

;

string

[] a

=

new

string

[ArraySize];

for

(

int

i

=

0

; i

<

ArraySize; i

) {

if

(i

!=

ArraySize

-

1

) { a[i]

=

str.Substring(i

*

Length , Length); }

//

對於不是整數倍StrTotalLength % Length取余的結果作為截取的長度

else

{ a[i]

=

str.Substring(i

*

Length , StrTotalLength

%

Length); }  }

return

a; }

catch

(Exception ex) { MessageBox.Show(ex.Message);

return

null

; } }  }  }

#endregion

#region

按鈕

private

void

button3_Click(

object

sender, EventArgs e) { //定義數組來接受方法傳回來的數組，數組的長度不好設定。

//string abc = "00001000020000300004000050000600007";            //const int CL = 30;            //string[] b = new string[30];            //b = CutString(abc, CL);            //int tiana = 0;            //if (abc.Length % CL == 0)            //{            //    tiana = abc.Length / CL;            //}            //else            //{            //    tiana = abc.Length / CL   1;            //}            //for (int i = 0; i < tiana; i  )            //{            //    listBox1.Items.Add(b[i]);            //} //定義動態數組ArrayList來接受方法傳回來的數組。數組長度很靈活            string str = "00001000020000300004000050000600007";            ArrayList al = new ArrayList();            const int CL = 10; //被截取的長度            al.AddRange(CutString(str, CL));            int strCount = 0;            if (str.Length % CL == 0)            {                strCount = str.Length/CL;            }            else            {                strCount = str.Length / CL 1;            }            for (int i = 0; i < strCount; i  )            {                listBox1.Items.Add(al[i]);            }

}

#endregion

字符

字符串

循環

DABAN RP主题是一个优秀的主题，极致后台体验，无插件，集成会员系统U19学习网站 » 對字符串進行相同長度循環截取 -开发者知识库