How to judge the length of mixed Characters in iOS

  • 2020-06-03 08:30:16
  • OfStack

Without further ado, I will post the code directly to you.

1. Code.


- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// The first 1 methods 
NSLog(@"--first-%i",[self convertToInt:@"123 I love you "]);
// The first 2 methods 
NSLog(@"--second--%ld",[self getToInt:@"123 I love you "]);
}
// Gets the length of the chinese-English mixed string   methods 1
- (int)convertToInt:(NSString*)strtemp
{
int strlength = 0;
char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
if (*p) {
p++;
strlength++;
}
else {
p++;
}
}
return strlength;
}
// Gets the length of the chinese-English mixed string   methods 2
- (NSInteger)getToInt:(NSString*)strtemp
{
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSData* da = [strtemp dataUsingEncoding:enc];
return [da length];
}

2. Output.


2015-10-19 15:36:43.730  Two ways to judge the length of mixed Chinese and English characters [9311:234111] --first-9
2015-10-19 15:36:43.736  Two ways to judge the length of mixed Chinese and English characters [9311:234111] --second--9

Here are two ways to judge the length of mixed Characters in iOS.


Related articles: