我正在尝试获取文本视图的第一句话。我有以下代码,但我得到一个越界错误。谢谢。或者有什么方法并不复杂。
-(IBAction)next:(id)sender
{
NSRange ran = [[tv.text substringFromIndex:lastLocation] rangeOfString:@". "];
if(ran.location != NSNotFound)
{
NSString * getRidOfFirstHalfString = [[tv.text substringFromIndex:lastLocation] substringToIndex:ran.location];
NSLog(@"%@",getRidOfFirstHalfString);
lastLocation+=getRidOfFirstHalfString.length;
}
答案 0 :(得分:4)
怎么样:
NSString *finalString = [[tv.text componentsSeparatedByString:@"."] objectAtIndex:0] // Get the 1st part (left part) of the separated string
浏览textview的文本,并通过在componentsSeperatedByString
上调用tv.text
将文本划分为单独的组件,以便找到句点。你想要第一个句子,它将是数组中的第0个对象。
答案 1 :(得分:4)
我知道您已经接受了这个问题的答案,但您可能要考虑使用文本视图tokenizer
而不是仅搜索字符串". "
。标记生成器会自动处理标点符号!
,?
和结束引号。您可以像这样使用它:
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextRange *range = [tokenizer rangeEnclosingPosition:textView.beginningOfDocument
withGranularity:UITextGranularitySentence
inDirection:UITextStorageDirectionForward];
NSString *firstSentence = [textView textInRange:range];
如果你想枚举所有句子,你可以这样做:
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextPosition *start = textView.beginningOfDocument;
while (![start isEqual:textView.endOfDocument]) {
UITextPosition *end = [tokenizer positionFromPosition:start toBoundary:UITextGranularitySentence inDirection:UITextStorageDirectionForward];
NSString *sentence = [textView textInRange:[textView textRangeFromPosition:start toPosition:end]];
NSLog(@"sentence=%@", sentence);
start = end;
}
答案 2 :(得分:1)
尝试检查实际找到的子字符串。
NSRange ran = [tv.text rangeOfString:@". "];
if(ran.location != NSNotFound)
{
NSString * selectedString = [tv.text substringToIndex:ran.location];
NSLog(@"%@",selectedString);
}
答案 3 :(得分:0)
您也可以尝试使用NSScanner:
NSString *firstSentence = [[NSString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:tv.text];
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"."];
[scanner scanUpToCharactersFromSet:set intoString:&firstSentence];
我不确定你是否想要这个,但是因为你想要第一句话,你可以追加一段时间(你可能知道如何做到这一点,但无论如何都不会有害):
firstSentence = [firstSentence stringByAppendingFormat:@"."];
希望这有帮助!
PS:如果它不适合您,可能文本视图实际上不包含任何文本。