我在字符串中有多个换行符。但是如果在字符串的开头或结尾处找到它,我只希望它被修剪。如果在它们之间发现则很好。怎么做?
答案 0 :(得分: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。
答案 1 :(得分: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];
答案 2 :(得分: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];
}
答案 3 :(得分:1)
您可以尝试使用hasPrefix
和hasSuffix
例如
NSString *str = @"\n This is a \n test \n";
if ([str hasPrefix:@"\n"])
{
//remove it
}
if ([str hasSuffix:@"\n"])
{
//remove it
}
答案 4 :(得分:1)
您可以使用stringByTrimmingCharactersInSet
修剪字符串两端的空格。
NSString* str = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];