views:

84

answers:

3

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

A: 

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.

St3fan
+1  A: 

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:

vodkhang
what about memory management?str = [str substringToIndex:100]; is this valid? or do I need to use copy?
Joey
that's valid, I think it will create another instance for substring and get it back to you. also, remember that str is autoreleased already. You should retain it if you want to keep it for long
vodkhang
Correction: `str` *may* be autoreleased already. If you previously wrote `str = [[NSString alloc] init];` or similar, it certainly isn't!But yes, assuming you're not leaking `str`, what you wrote is valid.
andyvn22
@andyvn22: ops, it is my mistake, I didn't see that he uses the same variable for the substring and the main string
vodkhang
A: 

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:@"COOL DOG", @"PUPPY", nil];

Loop Operation:

for (NSString *str in strs) 
{
    if (str.length > max)
        //get a modified string
        str = [str substringToIndex:str.length-(str.length-max)];
        NSLog(@"%@", str);
}

Results:

"COOL "

Hope, I understood right from your question.

Yoon Lee