tags:

views:

106

answers:

5

Does objective-c have raw strings?

Clarification: I mean raw strings similar to how Python has raw strings (follow the link and search for raw).

+1  A: 

Objective-C is a strict superset of C so you are free to use char * and char[] wherever you want (if that's what you call raw strings).

Ole Begemann
A: 

If you mean C-style strings, then yes.

Daniel A. White
No, he means RARRRRRRRRRRRRRRRRRRRRRR strings. heh = ]
Mr-sk
+3  A: 

Objective-C is a superset of C. So, the answer is yes. You can write

char* string="hello world";

anywhere. You can then turn it into an NSString later by

NSString* nsstring=[NSString stringWithUTF8String:string];
Yuji
+1  A: 

From your link explaining what you mean by "raw string", the answer is: there is no built in method for what you are asking.

However, you can replace occurrences of one string with another string, so you can replace @"\n" with @"\\n", for example. That should get you close to what you're seeking.

Dave DeLong
A: 

Like everyone said, raw ANSI strings are very easy. Just use simple C strings, or C++ std::string if you feel like compiling Objective C++.

However, the native string format of Cocoa is UCS-2 - fixed-width 2-byte characters. NSStrings are stored, internally, as UCS-2, i. e. as arrays of unsigned short. (Just like in Win32 and in Java, by the way.) The systemwide aliases for that datatype are unichar and UniChar. Here's where things become tricky.

GCC includes a wchar_t datatype, and lets you define a raw wide-char string constant like this:

wchar_t *ws = L"This a wide-char string.";

However, by default, this datatype is defined as 4-byte int and therefore is not the same as Cocoa's unichar! You can override that by specifying the following compiler option:

-fshort-wchar

but then you lose the wide-char C RTL functions (wcslen(), wcscpy(), etc.) - the RTL was compiled without that option and assumes 4-byte wchar_t. It's not particularly hard to reimplement these functions by hand. Your call.

Once you have a truly 2-byte wchar_t raw strings, you can trivially convert them to NSStrings and back:

wchar_t *ws = L"Hello";
NSString *s = [NSString stringWithCharacters:(const unichar*)ws length:5];

Unlike all other [stringWithXXX] methods, this one does not involve any codepage conversions.

Seva Alekseyev
Minor correction: the unichar in Cocoa is actually UTF-16 not UCS-2. The distinction between UCS-2 and UTF-16 is minor (since characters at or beyond Unicode 65536 are rare) but UCS-2 can only handle characters up to Unicode 65535. Cocoa uses UTF-16 and therefore can handle the whole Unicode range (using multi-character sequences).
Matt Gallagher
Are you saying that [NSString length] returns the length in characters as opposed to unichar's?
Seva Alekseyev