字符在NSString或NSMutableString中的位置 [英] Position of a character in a NSString or NSMutableString

查看:74
本文介绍了字符在NSString或NSMutableString中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了几个小时,还没有找到解决我问题的方法.我有一个如下所示的NSString:

I have searched for hours now and haven't found a solution for my problem. I have a NSString which looks like the following:

"spacer":["value1","value2"],"spacer":["value1","value2"],...

我想要做的是从字符串中删除[]字符.使用Objective-C似乎是不可能的.大多数其他编程语言都提供诸如strpos或indexOf之类的函数,这些函数使我可以搜索字符或字符串并找到其位置.但是在Objective-c中似乎没有什么可以解决的.

What I want to do is to remove the [ ] characters from the string. It's seems to be impossible with objective-c. Most other programming languages offer functions like strpos or indexOf which allow me to search for a character or string and locate the position of it. But there seems nothing to be like this in objective-c.

有人知道如何删除这些字符吗? 另外,字符串中还有[]个字符应保留,因此我不能只使用NSMutableString stringByReplacingOccurencesOfString:withString.我需要先搜索间隔字符串,然后仅删除接下来的两个[]字符.

Does anyone has an idea on how to remove these characters? Additionally there are [] characters in the string which should remain, so I can't just use NSMutableString stringByReplacingOccurencesOfString:withString. I need to search first for the spacer string and then remove only the next two [] chars.

谢谢您的帮助.

推荐答案

要查找字符串中某个字符串的出现,请使用

To find occurrences of a string within a string, use the rangeOfXXX methods in the NSString class. Then you can construct NSRanges to extract substrings, etc.

此示例仅删除示例字符串中的第一组打开/关闭括号...

This example removes only the first set of open/close brackets in your sample string...

NSString *original = @"\"spacer\": \[\"value1\", \"value2\"], \"spacer\": \[\"value1\", \"value2\"]";
NSLog(@"%@", original);

NSRange startRange = [original rangeOfString:@"\["];
NSRange endRange = [original rangeOfString:@"]"];

NSRange searchRange = NSMakeRange(0, endRange.location);
NSString *noBrackets = [original stringByReplacingOccurrencesOfString:@"\[" withString:@"" options:0 range:searchRange];
noBrackets = [noBrackets stringByReplacingOccurrencesOfString:@"]" withString:@"" options:0 range:searchRange];
NSLog(@"{%@}", noBrackets);

字符串编程指南有更多内容详细信息.
您可能也可以使用NSScanner类.

The String Programming Guide has more details.
You might alternatively also be able to use the NSScanner class.

这篇关于字符在NSString或NSMutableString中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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