1

我在一个字符串中有多个换行符。但我只希望在字符串的开头或结尾找到它时对其进行修剪。如果在两者之间找到它很好。怎么做?

4

5 回答 5

3

你需要使用:

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange;

目标将是@"\n"

替换将是@""

范围将是:

NSMakeRange(0,2); // for the beginning

NSMakeRange(string.length-2,2); // to the end

例如 -

//for the start
[yourString stringByReplacingOccurrencesOfString:@"\n" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,2)];

//for the end
[yourString stringByReplacingOccurrencesOfString:@"\n" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(yourString.length,2)];

您可以为该范围指定更长的长度,以确保它采用\n。

于 2012-06-27T06:14:31.293 回答
1
NSString* str = @"hdskfh   dsakjfh akhf kasdhfk asdfkjash fkadshf1234        ";
NSRange rng = [str rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: [str stringByReplacingOccurrencesOfString: @" " withString: @""]] options: NSBackwardsSearch];
str = [str substringToIndex: rng.location+1];
于 2012-06-27T06:14:55.933 回答
1

使用以下代码从开始和结束中删除 \n

NSString *str = @"\n test test \n test \n";

int firstOccurance = [str rangeOfString:@"\n"].location;
if (firstOccurance == 0) {
    str = [str substringFromIndex:1];
}

int lastOccurance = [str rangeOfString:@"\n" options:NSBackwardsSearch].location;
if (lastOccurance == str.length - 1) {
    str = [str substringToIndex:str.length - 2];
}
于 2012-06-27T06:15:29.530 回答
1

你可以尝试hasPrefixhasSuffix

例如

NSString *str = @"\n This is a \n test \n";

if ([str hasPrefix:@"\n"])
{
     //remove it
}

if ([str hasSuffix:@"\n"])
{
      //remove it
}
于 2012-06-27T06:20:55.033 回答
1

您可以使用stringByTrimmingCharactersInSet从字符串的两端修剪空白。

NSString* str = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
于 2012-06-27T06:26:11.940 回答