修剪具有多个条件的NSString

时间:2012-10-22 02:29:49

标签: iphone nsstring

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

  1. 修剪前导空格和换行符(基本上忽略任何前导空格和换行符)
  2. 将最多48个字符复制到新字符串中或直到遇到换行符。
  3. 我发现我可以使用代码从另一个SO问题中做出第一个要求:

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

    但是,我在完成第二项要求时遇到了麻烦。谢谢!

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分: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;
    }
}