Limiting NSString length without knowing the length
Limiting NSString length without knowing the length
- Subject: Limiting NSString length without knowing the length
- From: Jeffrey Mattox <email@hidden>
- Date: Thu, 13 Feb 2003 03:40:02 -0600
Executive summary:
Is there a NSString method that will truncate a string to a specified
length without me having to know its length beforehand?
Details:
I have a NSString of an unknown length from which I create a second,
formatted string that contains the first string. For example:
string2 = [NSString stringWithFormat:@"OLD: %@",string1];
However, I need to limit the length of string2 to a fixed value. The
documentation says stringWithFormat: uses printf()-like formats, but
specifying a precision of 20 does not work, like this:
string2 = [NSString stringWithFormat:@"OLD: %.20@", string1];
Apparently, stringWithFormat: doesn't implement all the printf() features.
So, I've looked at using this method:
[string1 substringToIndex:20]
But if the index is beyond the end of the string, it will raise an
error. That forces me to test the length first if I want to use that
method.
Unless I find a better way, this is my solution (convert to a C
string, limit the length, and then convert back to NSString):
char theCString[30];
sprintf(theCString,"%.20s",[string1 cString]); // limit
string2 = [NSString stringWithFormat:@"OLD: %@",
[NSString stringWithCString:theCString]];
But, is there a better way -- a method that will truncate a NSString
without me having to know its length beforehand?
Jeff
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.