swap char in NSString

Discussion in 'Mac Programming' started by smokyonion, Jan 25, 2010.

  1. smokyonion macrumors newbie

    Dec 13, 2009
    Dear all:

    I want to compare a NSString ( I get this NSString from [NSData description];)

    @"<55a1b2c3 aa>" this is supposed to be read from my serial device;

    but sometimes the computer will return @"<a1b2c3aa 55>"

    How do I quickly swap it as the original format @"<55a1b2c3 aa>"

    I have looked up the Apple Developer Reference but it seems there is no such swapping methods.. do I miss something?

    Any replies will be highly appreciated. Thank you guys.
  2. kainjow Moderator emeritus


    Jun 15, 2000
    Don't rely on the description method for anything beyond debugging.

    If you want to access the raw data of the NSData object, use the bytes or getBytes:length: methods. Once you have the data, you can cast it to another data type and use the various NSSwap* functions.
  3. smokyonion thread starter macrumors newbie

    Dec 13, 2009
    Guys: I found some methods and I tried to combine them to get what I want
    I know...it looks a little stupid but so far it works
    So is there a better way to do it?

    assuming hexString is @"<a1b2c3aa 55>"
    the finalString will be @"<55a1b2c3 aa>"
    NSString *stepOneString = [[NSString alloc] initWithString:@"<55"];
    NSString *stepTwoString = [hexString substringToIndex:9];
    NSString *stepThreeString = [stepTwoString substringFromIndex:1];
    NSString *stepFourString = [stepThreeString substringToIndex:6];
    NSString *appendString = [stepOneString stringByAppendingString:stepFourString];
    NSString *finalString = [appendString stringByAppendingString:@" aa>"];
    NSLog(@"Final: %@, length: %i",finalString, [finalString length]);
    kainjow, thank you so much for your reply,

    I'll look up the NSData reference and NSSwap try to figure it out. I'll keep this posted when I understand how to use it.
  4. Mac Player macrumors regular

    Jan 19, 2006
    Use the mutable classes, NSMutableString or NSMutableData.
  5. smokyonion thread starter macrumors newbie

    Dec 13, 2009
    Hello, Mac Player:

    Thank you for your reply, I have checked the NSMutableString, it looks like

    a nice way to solve my problem. Thank you so much. I really enjoy learning things from you guys. You rock~

    a Mac Programming newbie

Share This Page