When I write code, I encounter a string with a specified length in the original string. we usually use string. substring (), but this problem is that both Chinese characters and English characters are considered as a point length. because of this, sometimes what we want is not what we want.
I found it online and did not find it. So I wrote one myself. please correct me if there is any error. Thank you!
Private static string SubString (string stringToSub, int length ){
Regex regex = new Regex ("[\ u4e00-\ u9fa5] +", RegexOptions. Compiled );
Char [] stringChar = stringToSub. ToCharArray ();
StringBuilder sb = new StringBuilder ();
Int nLength = 0;
For (int I = 0; I <stringChar. Length; I ++ ){
If (regex. IsMatch (stringChar [I]). ToString ())){
Sb. Append (stringChar [I]);
NLength + = 2;
}
Else {
Sb. Append (stringChar [I]);
NLength = nLength + 1;
}
If (nLength> length)
Break;
}
Return sb. ToString ();
}