简体   繁体   English

如何从NSString中删除08十六进制字符

[英]How to remove 08 hexadecimal character from an NSString

I have a long string, and I would like to remove a specific hexadecimal character from it. 我有一个长字符串,我想从中删除一个特定的十六进制字符。

NSString * myString = @"longlongstringwithcharacters\"ofallsorts\"";

Any suggestions? 有什么建议么?

The hex character I am after is 08 , that corresponds to backspace. 我追求的十六进制字符是08 ,它对应于退格键。 How can I use code like the following to substitute it? 如何使用以下代码代替它? I have no idea on how to represent 08 in a string: 我不知道如何在字符串中表示08:

NSString *stringWithoutSpaces = [myString 
   stringByReplacingOccurrencesOfString:@" " withString:@""];

EDIT: 编辑:

I will try to clarify a bit more what I am trying to do.. 我将尝试澄清一些更多信息。

I am trying to remove all occurrences of a character that corresponds to 08 hex from the string that I receive as payload. 我试图从作为有效载荷接收的字符串中删除所有出现的与08十六进制相对应的字符。

The payload is in a string format and I found out the character by using Xcode debugger and view the hex codes of the string as there was an invalid character when trying to covert the NSData corresponding to the string to a NSDictionary. 有效载荷采用字符串格式,我尝试使用Xcode调试器找出字符,并查看字符串的十六进制代码,因为在尝试将与字符串相对应的NSData隐式转换为NSDictionary时,存在无效字符。

I am not sure how to phrase the problem correctly.. 我不确定如何正确表达问题。

- (NSString *)stringFromHexString:(NSString *)hexString {

    // The hex codes should all be two characters.
    if (([hexString length] % 2) != 0)
        return nil;

    NSMutableString *string = [NSMutableString string];

    for (NSInteger i = 0; i < [hexString length]; i += 2) {

        NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSInteger decimalValue = 0;
        sscanf([hex UTF8String], "%x", &decimalValue);
        [string appendFormat:@"%c", decimalValue];
    }

    return string;
}

Try this code...This will help you to convert Hex to string 试试这个代码...这将帮助您将十六进制转换为字符串

NSString * str = @"68656C6C6F";
NSMutableString * newString = [[[NSMutableString alloc] init] autorelease];
int i = 0;
while (i < [str length])
{
    NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
    int value = 0;
    sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
    [newString appendFormat:@"%c", (char)value];
    i+=2;
}

this will help u to convert Hex to NSString 这将帮助您将十六进制转换为NSString

This code worked for me: 这段代码对我有用:

    NSString * dataString = message.payloadString;
    NSString * wrongCharacter = [[NSString alloc] initWithFormat:@"%c", (char)0x08];
    dataString = [dataString stringByReplacingOccurrencesOfString:wrongCharacter withString:@""];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM