如何从 NSString 中提取/拆分数字和字符串 [英] How to extract/split numbers and string out from NSString

查看:61
本文介绍了如何从 NSString 中提取/拆分数字和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSString *text = @"randomtext12345"

I have a NSString *text = @"randomtext12345"

文本字符串将始终以字符串"(未知长度)开头,后跟数字"(整数类型).

The text string will always begins with 'string' (unknown length) and followed by 'number' (integer type).

文本之间没有分隔符",我如何检测哪个是字符串和整数?为了提取/分离/分离文本成为

There is no 'seperator' in between the text, how do I detect which is string and integer? in order to extract/seperate/seperate out the text to become

NSString *key = @"randomtext";
NSInteger value = 12345; 

推荐答案

这假设所有数值在最后都组合在一起(即randomtext"部分中没有数字).此外,我还没有包括错误检查以确保输入字符串 (text) 的格式正确.(即必须有一个字母部分后跟一个数字部分):

This assumes that all numeric values are grouped together at the end (i.e. there are no numbers in the "randomtext" portion). Also, I have not included error checking to make sure that the input string (text) is in the correct format. (i.e. there must be an alpha portion followed by a numeric portion):

NSString *text = @"randomtext12345";

NSRange beginningOfNumber = [text rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
if (beginningOfNumber.location == NSNotFound)
{
    return;
}

NSString *key           = [text substringToIndex:beginningOfNumber.location];
NSString *stringValue   = [text substringFromIndex:beginningOfNumber.location];
NSInteger value         = [stringValue integerValue];

// Output:  2012-07-29 14:08:56.504 Testing App[46439:fb03] key: randomtext, value: 12345

这篇关于如何从 NSString 中提取/拆分数字和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆