Re: Limiting NSString length without knowing the length
Re: Limiting NSString length without knowing the length
- Subject: Re: Limiting NSString length without knowing the length
- From: Marc Weil <email@hidden>
- Date: Thu, 13 Feb 2003 07:26:01 -0500
You don't need to convert it to a cstring to test its length, just use the
method [string1 length] that is part of all NSString objects.
Marc Weil
--
"Software exists to solve your problems. We exist to make the problems."
Microsoft
On 2/13/03 4:40 AM, "Jeffrey Mattox" <email@hidden> wrote:
>
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.
_______________________________________________
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.