Reputation: 65
Could anyone give some advise please.
In my iOS app I am parsing XML (with a help of third-party-library) and have a problem with extra whitespaces/newLines at the beginning/end of the strings. Initial string, that return this third-party-library, it's a C++ std::wstring
that I convert to NSString
(the encoding should be right as the content of new NSString
is equal to proper part of my XML-file). After the trim length of "empty" elements (that contain only whitespaces and new lines) doesn't become zero but change it's value by half.
The code is below....
std::wstring val;
NSString *initial = [[NSString alloc] initWithBytes:val.data() length:sizeof (wchar_t)*val.size() encoding:NSUTF16LittleEndianStringEncoding];
NSString *trimmed = [initial stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
If try to output like NSLog(@"bybyby'%@'bebebe", trimmed);
'bebebe have never displayed. Looks like that there are left some new lines, whitespaces that can't be detected.
Upvotes: 1
Views: 172
Reputation: 539745
wchar_t
is a 32-bit integer (on iOS and OS X), therefore you must use NSUTF32LittleEndianStringEncoding
for the conversion to NSString
.
Example:
std::wstring val (L" Hello World ");
NSString *initial = [[NSString alloc] initWithBytes:val.data() length:sizeof (wchar_t)*val.size() encoding:NSUTF32LittleEndianStringEncoding];
NSString *trimmed = [initial stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"'%@'", trimmed);
// Output: 'Hello World'
What probably happened in your case (with NSUTF16LittleEndianStringEncoding
)
is that every second character in the initial
string is a NUL character,
which acts as a terminator when printed.
Upvotes: 2