0

I get data from a UTF-8 encoded XML file, and I want to display every element in a UITableView . I want my cells to have the same size and display the 2 first text lines with the most data possible so I tried to remove the carriage returns.

In my cellForRow method I changed this :

[[myCell textLabel] setText:data];

By :

[[myCell textLabel] setText:[self correctData:data]];

Here is my correctData method :

- (NSString *) correctData : (NSString *) str
{
    NSMutableString *res = [NSMutableString stringWithFormat:@""];
    for(int i = 0 ; i < [str length] ; i++)
    {
        char car = [str characterAtIndex:i];
        if(car != 10 && car != 13) 
           [res appendString:[NSString stringWithFormat:@"%c",car]];
    }
    return res;
}

And this correctly removes the carriage returns, but it also alters the UTF-8 chars. For example, a bit of the initial string (str) :

Diplômé(e) d'Etat

And with this function it becomes :

DiplÙmÈ(e) d'Etat

What should I do ? Thanks.

1 Answer 1

4

NSString works with unichar characters that are stored on 16bits whereas char is only 8bits long. Converting an unichar to a char will alter all characters with a code point above U+00FF.

You can solve this issue by replacing char with unichar and %c with %C.

Edit: But that's not really efficient. You may better use regular expressions to replace all newline characters in once:

str = [str stringByReplacingOccurrencesOfString:@"[\r\n]+"
                                     withString:@""
                                        options:NSRegularExpressionSearch
                                           range:NSMakeRange(0, str.length)];
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing, that was so easy. Thanks a lot !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.