석진영
석진영

Reputation: 243

Insert a @"\n" in NSString

For example, if I start with this string:

NSString * labeltext = @"abcdefghijk";

I want this string change to @"abc\n def\n ghi \n jk".

I want @"\n" to be inserted at an interval of 3.

How can I accomplish this?

Upvotes: 0

Views: 423

Answers (1)

Ziminji
Ziminji

Reputation: 1306

Use a NSMutableString and then for loop through the original NSString.

NSMutableString *buffer = [[NSMutableString alloc] init];
int len = [labelText length];
for (i = 0; i < len; i++) {
    NSRange charAt = NSMakeRange(i,1);
    [buffer appendString: [labelText substringWithRange: charAt]];
    if ((i % 3) == 2) {
        [buffer appendString: @"\n"];
    }
}
labelText = (NSString *)buffer;

The above example is pure Objective-C. This can also be accomplished using C. Convert the NSString into a cstring and then loop through the array. For instance,

const char *str = [labelText UTF8String];
int len = strlen(str) - 1;
int pos = 0;
char buffer[(len * 2) + 1];
for (i = 0; i < len; i++) {
    char ch = str[i];
    buffer[pos] = ch;
    pos++;
    if ((i % 3) == 2) {
        buffer[pos] = '\n';
        pos++;
    }
}
buffer[pos] = '\0';
labelText = [NSString stringWithFormat: @"%s", buffer];

Upvotes: 3

Related Questions