我有一个字符串分3部分,1.) 是0位到10位. 2.) 是11位到20位. 3.) 是21位到25位 4.) 是26位到30位
我想把这个字符串的4部分分别取出,但是第2个部分是有可能出现中文的, 由于某个原因会出现这种情况:如果是2个中文,那么后面会有6个空格,如果是3个中文,那么后面会有4个空格.在这种情况家我没办法按照11到20位去截取字符串啊,因为单纯用string.Substring(11,20)很有可能会取到第3部分的.有什么办法能分别取到该字符串的4部分呢?
我想把这个字符串的4部分分别取出,但是第2个部分是有可能出现中文的, 由于某个原因会出现这种情况:如果是2个中文,那么后面会有6个空格,如果是3个中文,那么后面会有4个空格.在这种情况家我没办法按照11到20位去截取字符串啊,因为单纯用string.Substring(11,20)很有可能会取到第3部分的.有什么办法能分别取到该字符串的4部分呢?
String str="你的字符串";
string str2=""; //第二部分字符串
switch(str.Length)
{
case 25: //5个中文字
str2=str.Substring(10,5);
break;
case 26: //4个中文字
str2=str.Substring(10,6);
break;
case 27: //3个中文字
str2=str.Substring(10,7);
break; //2个中文字
case 28:
str2=str.Substring(10,8);
break;
case 29: //1个中文字
str2=str.Substring(10,9);
break;
case 30: //无中文字
str2=str.Substring(10,10);
break;
}
关键就是当有中文字的话再给我之前,一个中文字抵2个字符,所以当轮到我操作的时候他的长度就不对了,不知道你明白我的意思?加空格不是我能控制的,是另一个系统生成的格式,它会把一个中文字抵2个字符,最终会得出:如果是2个中文,那么后面会有6个空格,如果是3个中文,那么后面会有4个空格.但是格式长度还是10,最要命的就是在中间部分出现啊,如果在开头或结尾的话还好办点.
转换成 byte[] 数组在截取.
{
this.textBox1.Text="1234567890第二 abcdefghij";
} private void button1_Click(object sender, System.EventArgs e)
{
byte[] bytes=System.Text.Encoding.Default.GetBytes(this.textBox1.Text);
string str1=System.Text.Encoding.Default.GetString(bytes,0,10);
string str2=System.Text.Encoding.Default.GetString(bytes,10,10);
string str3=System.Text.Encoding.Default.GetString(bytes,20,5);
string str4=System.Text.Encoding.Default.GetString(bytes,25,5);
this.listBox1.Items.Add(str1);
this.listBox1.Items.Add(str2);
this.listBox1.Items.Add(str3);
this.listBox1.Items.Add(str4);
}
}
private void UpendStr( ref string refStr )
{
string _temp = "" ;
for( int i = refStr.Length -1 ; i >= 0 ; i -- )
{
_temp += refStr[ i ] ;
}
refStr =_temp ;
} private void StrSplit( string inSource ,
ref string refFirst ,
ref string refSecond ,
ref string refThird ,
ref string refFourth )
{
refFirst = inSource.Substring( 0 , 10 ) ; string _upendSource = inSource ;
UpendStr( ref _upendSource ) ; refThird = _upendSource.Substring( 5 , 5 ) ;
UpendStr( ref refThird ) ; refFourth = _upendSource.Substring( 0 , 5 ) ;
UpendStr( ref refFourth ) ; string _temp = _upendSource.Remove( 0 , 10 ) ;
UpendStr( ref _temp ) ;
refSecond = _temp.Remove( 0 , 10 ) ;
}