I have number of line breaks in a string. But I only want it to be trimmed if it is found at the start of string or at the end. It is fine if it is found in between. How to do that?
Asked
Active
Viewed 602 times
5 Answers
3
You need to use:
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange;
The target will be @"\n"
The replacement will be @""
The range will be:
NSMakeRange(0,2); // for the beginning
and
NSMakeRange(string.length-2,2); // to the end
For example -
//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)];
You can specify a longer length to the range to be sure that it is taking the \n.

Matt Kantor
- 1,704
- 1
- 19
- 37

shannoga
- 19,649
- 20
- 104
- 169
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];

user1478583
- 342
- 2
- 7
1
Use the following code to remove the \n from start and end
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];
}

Omar Abdelhafith
- 21,163
- 5
- 52
- 56
1
You can try with hasPrefix
and hasSuffix
for example
NSString *str = @"\n This is a \n test \n";
if ([str hasPrefix:@"\n"])
{
//remove it
}
if ([str hasSuffix:@"\n"])
{
//remove it
}

Maulik
- 19,348
- 14
- 82
- 137
-
-
change `if` to `while`: `while( [ str hasPrefix:@"\n" ] ) { str = [ str substringFromIndex:1 ] ; }` – nielsbot Jun 27 '12 at 06:26
-
and `while ( [ str hasSuffix:@"\n" ] ) { str = [ str substringWithRange:(NSRange){ 0, str.length - 1 } ] ; }` – nielsbot Jun 27 '12 at 06:27
1
You can use stringByTrimmingCharactersInSet
to trim whitespace from both ends of the string.
NSString* str = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Robotnik
- 3,643
- 3
- 31
- 49