使用 Objective-C 分割输入字符串
我在 iPhone 项目中使用 ASIHTTPREQUEST 来获取一些看起来像这样的数据(作为 NSString):
name:daniel, age:22, occupation:runner, name:greg, age:32, occupation:plumber
并且我想将它们解析为字典或数组,以便我可以获得所有名称或所有职业等。
我该怎么办这在 Objective-C 中吗?
谢谢
I am using ASIHTTPREQUEST in an iPhone project to get some data that looks something like this (as an NSString):
name:daniel, age:22, occupation:runner, name:greg, age:32, occupation:plumber
and I want to parse these into dictionaries or arrays so that I can get all names, or all occupations etc.
How can I do this in objective-c?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种方法是使用 NSString 的
-componentsSeparatedByString:
方法以及分隔符字符串@", "
将字符串分解为单独的子字符串,每个子字符串对应一个键/值对。然后,您可以再次使用它与分隔符@":"
将每个子字符串分解为键和值,并将它们插入字典中。另一种方法是使用 NSScanner 扫描输入字符串,按顺序获取键和值。
One way is to use NSString's
-componentsSeparatedByString:
method with a separator string of@", "
to break the string up into separate substrings, one for each key/value pair. Then you can use it again with a separator of@":"
to break each substring into a key and a value, and insert these into a dictionary.Another way is to use NSScanner to scan through your input string, taking the keys and values sequentially.