Nitish
Nitish

Reputation: 14123

NSString trim \n

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?

Upvotes: 1

Views: 604

Answers (5)

shannoga
shannoga

Reputation: 19869

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.

Upvotes: 3

Robotnik
Robotnik

Reputation: 3820

You can use stringByTrimmingCharactersInSet to trim whitespace from both ends of the string.

NSString* str = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Upvotes: 1

Maulik
Maulik

Reputation: 19418

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
}

Upvotes: 1

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

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];
}

Upvotes: 1

user1478583
user1478583

Reputation: 342

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];

Upvotes: 1

Related Questions