Joey
Joey

Reputation: 85

NSString length limit

How can I limit the length of a NSString? I would like to keep it below to equal to 100 characters/

Upvotes: 5

Views: 5006

Answers (3)

Yoon Lee
Yoon Lee

Reputation: 2039

Here is the sample of fundamental manipulate string size.

Declare maximum string length:

int max = 5;

Let's assume have list of strings in array:

NSArray *strs = [NSArray arrayWithObjects:@"My Little Puppy", @"Yorkerz", nil];

Loop Operation:

[strs enumerateObjectsUsingBlock:^(NSString *str, NSUInteger idx, BOOL *stop) {
    if (str.length > max)
        //get a modified string
        str = [str substringToIndex:str.length-(str.length-max)];
    NSLog(@"%@", str);
}];

Results:

"My Li" and "Yorke"

Hope, I understood right from your question.

Upvotes: 8

vodkhang
vodkhang

Reputation: 18741

Then you will have to check for the length: before you put into the NSString. Then if the length is more than 100, you use substringToIndex:

Upvotes: 2

Stefan Arentz
Stefan Arentz

Reputation: 34945

Then do not add more than 100 characters.

If you have an existing string that you wish to shorten, then you can use the substringToIndex: method to create a shorter string.

Upvotes: 0

Related Questions