Re: How to get the length of a string?
Re: How to get the length of a string?
- Subject: Re: How to get the length of a string?
- From: Rainer Brockerhoff <email@hidden>
- Date: Tue, 21 Aug 2001 13:20:44 -0300
>
From: "Todd Heberlein" <email@hidden>
>
Date: Mon, 20 Aug 2001 10:55:32 -0700
>
>
Look in the on-line documentation for NSString under Foundation. There
>
are a couple of methods, the most obvious being "length".
>
n = [my_string length];
>
n = [my_string cStringLength];
>
>
If you want to have fun, you can return a C-style string and do a
>
strlen() on it. :-)
>
n = strlen([my_string cString]);
Unfortunately both methods can return "wrong" results, depending on how you define "length". Do you need to do old-style C stuff with the string, allocate a buffer for it, a database field, or something?
n = [my_string length];
will return the number of Unicode characters in the string, which does NOT translate necessarily to the number of character glyphs - accented/umlauted characters correspond to two Unicode characters, but a single glyph, for instance.
n = [my_string cStringLength];
will throw an exception if there's a non-low-ASCII character anywhere in the NSString. Use:
n = strlen([my_string lossyCString]);
which _may_ work for Western European languages.
If you're handling file paths, always use:
n = strlen([my_string UTF8String]);
--
Rainer Brockerhoff <email@hidden>
Belo Horizonte, Brazil
"In the affairs of others even fools are wise
In their own business even sages err."
http://www.brockerhoff.net/ (updated July 2000)