我一直试图弄清楚如何从指定范围(即光标的当前位置)中找到字符的出现。
我知道如何找到光标的当前位置使用
NSRange cursorPosition = [textView.text selectedRange];
但我想弄清楚如何从
cursorPosition
向后搜索.我想要做的是,例如,如果我有一个字符串:
NSString *string = @"Hello I am tagging @xyz to notify them of the tag"
假设在
string
,光标的位置就在 "to"
之前,我想从光标所在位置搜索到@
的位置在字符串中并从 cursorPosition
中获取子字符串至@
.如果我的描述含糊不清或写得不好,请告诉我,我会进一步解释。
任何帮助都会很棒!非常感谢!
编辑:非常感谢您的所有时间和回复!
最佳答案
只需使用 rangeOfString:options:range:
.
// Get the current selection range
NSRange cursorPosition = [textView.text selectedRange];
if (cursorPosition.location != NSNotFound) {
// Build range from start of text up to the start of the selection
NSRange searchRange = NSRangeMake(0, cursorPosition.location);
// Find the desired substring within the range
NSRange matchRange = [textView.text rangeOfString:@"@" options:NSBackwardsSearch range:searchRange];
if (matchRange.location != NSNotFound) {
// Build range starting with the found substring up to the start of the selection
NSRange textRange = NSRangeMake(matchRange.location, searchRange.length - matchRange.location);
// Get the text in the desired range
NSString *matchingText = [textView.text substringInRange:textRange];
NSLog(@"Matching text to caret is %@", matchingText);
} else {
NSLog(@"No match up to the caret");
}
} else {
NSLog(@"No selection");
}
请注意,此代码查找 TextView 中任何当前选择的开头。如果您想在当前选择中进行搜索,则需要进行相应调整。
关于ios - NSString 从 UITextView 中的光标位置搜索字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33220768/