0

我很难从 NSString 中修剪一些字符。给定一个包含文本的现有文本视图,要求是:

  1. 修剪前导空格和换行符(基本上忽略任何前导空格和换行符)
  2. 最多将 48 个字符复制到新字符串中,或​​者直到遇到换行符。

我发现我可以使用代码在这里完成另一个 SO 问题的第一个要求:

NSRange range = [textView.text rangeOfString:@"^\\s*" options:NSRegularExpressionSearch];
NSString *result = [textView.text stringByReplacingCharactersInRange:range withString:@""];

但是,我在执行第二个要求时遇到了麻烦。谢谢!

4

2 回答 2

1

这将做你想做的事。它也是修剪前导空格和换行符的更简单方法。

NSString *text = textView.text;

//remove any leading or trailing whitespace or line breaks
text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

//find the the range of the first occuring line break, if any.
NSRange range = [text rangeOfString:@"\n"];

//if there is a line break, get a substring up to that line break
if(range.location != NSNotFound)
    text = [text substringToIndex:range.location];
//else if the string is larger than 48 characters, trim it
else if(text.length > 48)
    text = [text substringToIndex:48];
于 2012-10-22T02:42:53.600 回答
1

这应该有效。基本上它的作用是遍历 textview 文本中的字符并检查它当前所在的字符是否是换行符。它还检查它是否已达到 48 个字符。如果该字符不是换行符且尚未达到 48 个字符,则将该字符添加到结果字符串中:

NSString *resultString = [NSString string];
NSString *inputString = textView.text;

for(int currentCharacterIndex = 0; currentCharacterIndex < inputString.length; currentCharacterIndex++) {

    unichar currentCharacter = [inputString characterAtIndex:currentCharacterIndex];
    BOOL isLessThan48 = resultString.length < 48;
    BOOL isNewLine = (currentCharacter == '\n');

    //If the character isn't a new line and the the result string is less then 48 chars
    if(!isNewLine && isLessThan48) {

        //Adds the current character to the result string
        resultString = [resultString stringByAppendingFormat:[NSString stringWithFormat:@"%C", currentCharacter]];
    } 

    //If we've hit a new line or the string is 48 chars long, break out of the loop
    else {
        break;
    }
}
于 2012-10-22T02:44:03.860 回答