public static string Cutbytestring (String Str,int len)
{
String result=string. empty;//result of Final return
if (string. IsNullOrEmpty (str)) {return result;}
int Bytelen=system.text.encoding.default.getbytecount (str);//single-byte character length
int CHARLEN=STR. length;//string length when the character is treated equally
int bytecount=0;//Record Read progress
int pos=0;//record intercept position
if (Bytelen>len)
{
for (int i=0;i<charlen;i++)
{
if (Convert.ToInt32 (str. ToCharArray () [i] >255)//2 by Chinese characters
{bytecount+=2;}
else//by English characters plus 1
{bytecount+=1;}
if (Bytecount>len)//Only write down last valid location when exceeding
{
Pos=i;
Break
}
else if (Bytecount==len)//write down the current location
{
pos=i+1;
Break
}
}
if (pos>=0)
{Result=str. Substring (0,pos); }
}
Else
{result=str;}
return result;
}
public static string Cutbytestring (String str,int startindex,int len)
{
String result=string. empty;//result of Final return
if (string. IsNullOrEmpty (str)) {return result;}
int Bytelen=system.text.encoding.default.getbytecount (str);//single-byte character length
int CHARLEN=STR. length;//string length when the character is treated equally
if (startindex==0)
{return cutbytestring (Str,len);}
else if (Startindex>=bytelen)
{return result;}
else//startindex < Bytelen
{
int Alllen=startindex+len;
int bytecountstart=0;//Record Read progress
int bytecountend=0;//Record Read progress
int startpos=0;//record intercept position
int endpos=0;//record intercept position
for (int i=0;i<charlen;i++)
{
if (Convert.ToInt32 (str. ToCharArray () [i] >255)//2 by Chinese characters
{bytecountstart+=2;}
else//by English characters plus 1
{bytecountstart+=1;}
if (Bytecountstart>startindex)//Only write down last valid location when exceeding
{
Startpos=i;
alllen=startindex+len-1;
Break
}
else if (bytecountstart==startindex)//write down the current location
{
startpos=i+1;
Break
}
}
if (Startindex+len<=bytelen)//intercept characters within the total length
{
for (int i=0;i<charlen;i++)
{
if (Convert.ToInt32 (str. ToCharArray () [i] >255)//2 by Chinese characters
{bytecountend+=2;}
else//by English characters plus 1
{bytecountend+=1;}
if (Bytecountend>alllen)//Only write down last valid location when exceeding
{
Endpos=i;
Break
}
else if (Bytecountend==alllen)//write down the current location
{
endpos=i+1;
Break
}
}
Endpos=endpos-startpos;
}
else if (Startindex+len>bytelen)//intercept character exceeds total length
{
Endpos=charlen-startpos;
}
if (endpos>=0)
{Result=str. Substring (Startpos,endpos); }
}
return result;
}
Call:
private void Button1_Click (Object Sender,eventargs e)
{
String s= "12,345,678";
S=cutbytestring (s,5);
MessageBox.Show (s); Output "123"
S=cutbytestring (s,3,5);
MessageBox.Show (s); Output "2,345"
}
C # intercepts strings by byte intercept substring