ios Objective-C:如何提取字符串的一部分(例如以“#”开头)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6825834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C: How to extract part of a String (e.g. start with '#')
提问by Zhen
I have a string as shown below,
我有一个如下所示的字符串,
NSString * aString = @"This is the #substring1 and #subString2 I want";
How can I select only the text starting with '#' (and ends with a space), in this case 'subString1' and 'subString2'?
如何仅选择以“#”开头(并以空格结尾)的文本,在本例中为“subString1”和“subString2”?
Note: Question was edited for clarity
注意:为了清楚起见,对问题进行了编辑
回答by ughoavgfhw
You can do this using an NSScannerto split the string up. This code will loop through a string and fill an array with substrings.
您可以使用NSScanner来拆分字符串。这段代码将遍历一个字符串并用子字符串填充一个数组。
NSString * aString = @"This is the #substring1 and #subString2 I want";
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanUpToString:@"#" intoString:nil]; // Scan all characters before #
while(![scanner isAtEnd]) {
NSString *substring = nil;
[scanner scanString:@"#" intoString:nil]; // Scan the # character
if([scanner scanUpToString:@" " intoString:&substring]) {
// If the space immediately followed the #, this will be skipped
[substrings addObject:substring];
}
[scanner scanUpToString:@"#" intoString:nil]; // Scan all characters before next #
}
// do something with substrings
[substrings release];
Here is how the code works:
以下是代码的工作原理:
- Scan up to a #. If it isn't found, the scanner will be at the end of the string.
- If the scanner is at the end of the string, we are done.
- Scan the # character so that it isn't in the output.
- Scan up to a space, with the characters that are scanned stored in
substring
. If either the # was the last character, or was immediately followed by a space, the method will return NO. Otherwise it will return YES. - If characters were scanned (the method returned YES), add
substring
to thesubstrings
array. - GOTO 1
- 最多扫描一个#。如果未找到,则扫描仪将位于字符串的末尾。
- 如果扫描仪在字符串的末尾,我们就完成了。
- 扫描 # 字符,使其不在输出中。
- 最多扫描一个空格,扫描的字符存储在
substring
. 如果 # 是最后一个字符,或者后面紧跟一个空格,则该方法将返回 NO。否则它将返回YES。 - 如果字符被扫描(该方法返回 YES),则添加
substring
到substrings
数组中。 - 转到 1
回答by Varun Chatterji
[aString substringWithRange:NSMakeRange(13, 10)]
would give you substring1
会给你 substring1
You can calculate the range using:
您可以使用以下方法计算范围:
NSRange startRange = [aString rangeOfString:@"#"];
NSRange endRange = [original rangeOfString:@"1"];
NSRange searchRange = NSMakeRange(startRange.location , endRange.location);
[aString substringWithRange:searchRange]
would give you substring1
会给你 substring1
Read more: Position of a character in a NSString or NSMutableString
阅读更多: 字符在 NSString 或 NSMutableString 中的位置
and
和
http://iosdevelopertips.com/cocoa/nsrange-and-nsstring-objects.html
http://iosdevelopertips.com/cocoa/nsrange-and-nsstring-objects.html
回答by Rob Caraway
Pretty simple, easy to understand version avoiding NSRange
stuff:
非常简单,易于理解的版本避免使用NSRange
:
NSArray * words = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSMutableArray * mutableWords = [NSMutableArray new];
for (NSString * word in words){
if ([word length] > 1 && [word characterAtIndex:0] == '#'){
NSString * editedWord = [word substringFromIndex:1];
[mutableWords addObject:editedWord];
}
}
回答by Brain2000
Assuming that you are looking to find the first string that starts with a pound, and ends with a space, this might work. I don't have XCode in front of me, so forgive me if there's a syntax error or length off by 1 somewhere:
假设您要查找以磅开头并以空格结尾的第一个字符串,这可能会奏效。我面前没有 XCode,所以如果某个地方有语法错误或长度减少 1,请原谅我:
-(NSString *)StartsWithPound:(NSString *)str {
NSRange range = [str rangeOfString:@"#"];
if(range.length) {
NSRange rangeend = [str rangeOfString:@" " options:NSLiteralSearch range:NSMakeRange(range.location,[str length] - range.location - 1)];
if(rangeend.length) {
return [str substringWithRange:NSMakeRange(range.location,rangeend.location - range.location)];
}
else
{
return [str substringFromIndex:range.location];
}
}
else {
return @"";
}
}
回答by Krys Jurgowski
Another simple solution:
另一个简单的解决方案:
NSRange hashtag = [aString rangeOfString:@"#"];
NSRange word = [[aString substringFromIndex:hashtag.location] rangeOfString:@" "];
NSString *hashtagWord = [aString substringWithRange:NSMakeRange(hashtag.location, word.location)];
回答by Septronic
This is what I'd do:
这就是我要做的:
NSString *givenStringWithWhatYouNeed = @"What you want to look through";
NSArray *listOfWords = [givenStringWithWhatYouNeed componentsSeparatedByString:@" "];
for (NSString *word in listOfWords) {
if ([[word substringWithRange:NSMakeRange(0, 1)]isEqualToString:@"#"]) {
NSString *whatYouWant = [[word componentsSeparatedByString:@"#"]lastObject];
}
}
Then you can do what you need with the whatYouWant
instances. If you want to know which string it is (if it's the substring 1 or 2), check the index of of word
string in the listOfWords
array.
然后,您可以对whatYouWant
实例执行所需的操作。如果您想知道它是哪个字符串(如果它是子字符串 1 或 2),请检查数组中word
字符串的索引listOfWords
。
I hope this helps.
我希望这有帮助。
回答by Enrico Cupellini
A general and simple code to select all the words starting with "#" in a NSString is:
用于选择 NSString 中所有以“#”开头的单词的通用且简单的代码是:
NSString * aString = @"This is the #substring1 and #subString2 ...";
NSMutableArray *selection=@[].mutableCopy;
while ([aString rangeOfString:@"#"].location != NSNotFound)
{
aString = [aString substringFromIndex:[aString rangeOfString:@"#"].location +1];
NSString *item=([aString rangeOfString:@" "].location != NSNotFound)?[aString substringToIndex:[aString rangeOfString:@" "].location]:aString;
[selection addObject:item];
}
if you still need the original string you can do a copy. The inline conditional is used in case your selected item is the last word
如果您仍然需要原始字符串,您可以复制一份。如果您选择的项目是最后一个词,则使用内联条件