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
2010-08-23 02:55:04
+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
2010-08-23 02:57:48
what about memory management?str = [str substringToIndex:100]; is this valid? or do I need to use copy?
Joey
2010-08-23 03:38:30
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
2010-08-23 03:40:58
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
2010-08-23 04:55:16
@andyvn22: ops, it is my mistake, I didn't see that he uses the same variable for the substring and the main string
vodkhang
2010-08-23 05:35:44
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
2010-08-23 11:27:21