Search code examples
objective-cnsstringcut

Cut NSString to carriage return


I have NSString example:

@"Hello, Hello

How are you?"

I need to keep them words to transfer carriage. That is @"Hello, Hello"

I have text from UIWebView. Text I get

NSString *myText = [self.webview stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerText"];
    NSLog(@"my text -> %@",myText);

Thanks


Solution

  • Alexander, if I'm reading this right, you want to cut string before new line symbol comes.

    eg.
    Before:"Hello
    World"
    After:"Hello"

    If so you can use this NSString category:

    NSString+CutToNewLine.h

    #import <Foundation/Foundation.h>
    
    @interface NSString (CutToNewLine)
    - (NSString *)cutToNewLine;
    @end
    

    NSString+CutToNewLine.m

    #import "NSString+CutToNewLine.h"
    
    
    @implementation NSString (CutToNewLine)
    - (NSString *)cutToNewLine
    {
        NSRange newLineRange = [self rangeOfString: @"\n"];
        NSRange stringBeforeNewLineRange = NSMakeRange(0, newLineRange.location);
    
        NSString *resultString = [self substringWithRange: stringBeforeNewLineRange];
    
        return resultString;
    }
    
    @end
    

    Results

     NSString *s = @"Hello\nWorld!";
     NSLog(@"%@", s);
     NSLog(@"%@", [s cutToNewLine]);
    

    Output

    2013-03-04 20:02:17.075 NSStringCut[734:f07] Hello
    World!
    2013-03-04 20:02:17.076 NSStringCut[734:f07] Hello
    
    Process finished with exit code 0
    

    Code sample you can find here

    BR
    Eugene.