Removing New Line Characters from Nsstring

Removing new line characters from NSString

Split the string into components and join them by space:

NSString *newString = [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@" "];

Remove beginning and trailing new line characters from NSString

Use stringByTrimmingCharactersInSet method of nsstring which Returns a new string made by removing from both ends of the receiver characters contained in a given character set.

Swift

yourString = yourString.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)

Objective-C

  yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]

How do I remove new line characters from a string?

stringByReplacingOccurrencesOfString does not modify textLine

NSString *strippedTextLine = [textLine stringByReplacingOccurrencesOfString:@"\n" withString:@""];

Or

NSString *textLine = @"My cool text\n";
textLine = [textLine stringByReplacingOccurrencesOfString:@"\n" withString:@""];

Remove leading and trailing newline characters from NSString

text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

This trims also whitespace.
If you want to keep whitespace, just use the newlineCharacterSet instead.

Edited, as per @ghettopia correct suggestion about using the newlineCharacterSet instead of creating. Custom one.

NSString replace repeated newlines with single newline

You might use NSRegularExpression. This is the most simple and elegant way:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\n+" options:0 error:NULL];
NSString *newString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@"\n"];

Remove newline character from first line of NSString

This should do the trick:

NSString * ReplaceFirstNewLine(NSString * original)
{
NSMutableString * newString = [NSMutableString stringWithString:original];

NSRange foundRange = [original rangeOfString:@"\n"];
if (foundRange.location != NSNotFound)
{
[newString replaceCharactersInRange:foundRange
withString:@""];
}

return [[newString retain] autorelease];
}


Related Topics



Leave a reply



Submit