How to remove 08 hexadecimal character from an NSString - ios

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. How can I use code like the following to substitute it? I have no idea on how to represent 08 in a string:
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.
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.
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

This code worked for me:
NSString * dataString = message.payloadString;
NSString * wrongCharacter = [[NSString alloc] initWithFormat:#"%c", (char)0x08];
dataString = [dataString stringByReplacingOccurrencesOfString:wrongCharacter withString:#""];

Related

How to convert HEX to NSString in Objective-C j?

I have a NSString with hex string like "&# x62a;&# x631;&# x642;&# x628;" which means "ترقب".
Now I want to convert the hex string into another NSString object which shows "ترقب". How to do that ?
- (NSMutableString *) hextostring:(NSString *) str{
//ت
NSMutableString *string = [[NSMutableString alloc]init];
str = [str stringByReplacingOccurrencesOfString:#"&#" withString:#"0"];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"z;"];
NSArray *arr = [str componentsSeparatedByString:#";"];
for (int i =0; i<[arr count]; i++) {
if ([[arr objectAtIndex:i] isEqualToString:#"z"]) {
[string appendString:#" "];
} else {
unsigned x;
[[NSScanner scannerWithString: [arr objectAtIndex:i]] scanHexInt: &x];
[string appendFormat:#"%C",(unichar)x];
}
}
NSLog(#"%#",string);
return string;
}
Your string looks like HTML escape sequences, except for the spaces after the #'s. If this is really what you have (check something isn't just displaying Unicode as escapes) then there is a myriad of ways to convert it. You can just process the string picking out the hex chars and producing UniChar values from them, etc.
If you want a high-level, maybe somewhat long-winded approach, you and try:
- (NSString *)decodeHTMLescapes:(NSString *)raw
{
NSString *nospaces = [raw stringByReplacingOccurrencesOfString:#" " withString:#""]; // one way to remove the spaces
const char *cString = [nospaces UTF8String]; // C string
NSData *bytes = [[NSData alloc] initWithBytesNoCopy:(void *)cString length:strlen(cString) freeWhenDone:NO]; // as bytes
NSAttributedString *attributed = [[NSAttributedString alloc] initWithHTML:bytes documentAttributes:nil]; // interpret as HTML
NSString *decoded = attributed.string; // and finally as plain text
return decoded;
}
That (a) strips the spaces, (b) creates a C string and (c) creates a byte buffer, all that so we can (d) interpret that byte buffer as HTML, and (e) finally gets the string back. The use of initWithBytesNoCopy:length:freeWhenDone: is to reduce the copying all this does.
Use it like:
NSString *raw = #"&# x62a;&# x631;&# x642;&# x628;";
NSString *decoded = [self decodeHTMLescapes:raw];
NSLog(#"%# -> %#", raw, decoded);
HTH

How to convert a currency string to number

I have the following string:
R$1.234.567,89
I need it to look like: 1.234.567.89
How can i do this?
This is what i tried:
NSString* cleanedString = [myString stringByReplacingOccurrencesOfString:#"." withString:#""];
cleanedString = [[cleanedString stringByReplacingOccurrencesOfString:#"," withString:#"."]
stringByTrimmingCharactersInSet: [NSCharacterSet symbolCharacterSet]];
It works, but I think there must be a better way. Suggestions?
If your number always after $, but you got more characters before it, you can make it like this:
NSString* test = #"R$1.234.567,89";
NSString* test2 = #"TESTERR$1.234.567,89";
NSString* test3 = #"HEllo123344R$1.234.567,89";
NSLog(#"%#",[self makeCleanedText:test]);
NSLog(#"%#",[self makeCleanedText:test2]);
NSLog(#"%#",[self makeCleanedText:test3]);
method is:
- (NSString*) makeCleanedText:(NSString*) text{
int indexFrom = 0;
for (NSInteger charIdx=0; charIdx<[text length]; charIdx++)
if ( '$' == [text characterAtIndex:charIdx])
indexFrom = charIdx + 1;
text = [text stringByReplacingOccurrencesOfString:#"," withString:#"."];
return [text substringFromIndex:indexFrom];
}
result is:
2013-10-20 22:35:39.726 test[40546:60b] 1.234.567.89
2013-10-20 22:35:39.728 test[40546:60b] 1.234.567.89
2013-10-20 22:35:39.731 test[40546:60b] 1.234.567.89
If you just want to remove the first two characters from your string you can do this
NSString *cleanedString = [myString substringFromIndex:2];

Shuffling a greek word in iOS prints unknown symbols

I want to shuffle a string that contains Greek characters:
Here is my code:
- (void)shuffle {
NSLog(#"Will shuffle :%#",anagram2);
NSData* data = [anagram2 dataUsingEncoding:NSWindowsCP1253StringEncoding];
NSLog(#"after encoding :%#",anagram2);
NSString *someString = [[NSString alloc]initWithData:data encoding:NSWindowsCP1253StringEncoding];
NSLog(#"Greek word:%#",someString);
int length = anagram2.length;
NSMutableArray *letters = [[NSMutableArray alloc] init];
for (int i = 0; i< length; i++) {
NSString *letter = [NSString stringWithFormat:#"%c", [someString characterAtIndex:i]];
NSLog(#"Character:%#",letter);
[letters addObject:someLetter];
}
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
//NSLog(#"Value is : %i", value);
[letters exchangeObjectAtIndex:i withObjectAtIndex:value];
}
}
I can see the Greek word correctly. But the shuffling does not work. How can I extract each character and add it to a letters array. It works with English words but not with Greek ones, so I suppose that I should replace this:
NSString *letter = [NSString stringWithFormat:#"%c", [someString characterAtIndex:i]];
with something else.
The main problem seems to me that
[NSString stringWithFormat:#"%c":...]
works only with ASCII characters. You would have to use at least the "%C" format to make
it work with Unicode characters.
Also the conversion from NSString to NSData and back would fail as soon as you have any characters that are not available in the specified encoding.
The following method avoids all these problems and should work with arbitrary Unicode characters
(even with Emojis, which are internally represented as 2 UTF-16 characters):
NSString *string = #"Ελλάδα 😄";
NSLog(#"Will shuffle: %#", string);
// Convert string to an array of (32 bit) Unicode characters:
NSMutableData *data = [[string dataUsingEncoding:NSUTF32BigEndianStringEncoding] mutableCopy];
uint32_t *letters = [data mutableBytes];
int length = [data length]/4; // The number of 32-bit Unicode characters
// Shuffle the Unicode characters:
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
uint32_t tmp = letters[i];
letters[i] = letters[value];
letters[value] = tmp;
}
// Create new string from the shuffled Unicode characters:
NSString *shuffled = [[NSString alloc] initWithData:data encoding:NSUTF32BigEndianStringEncoding];
NSLog(#"Shuffled: %#", shuffled);
Output:
Will shuffle: Ελλάδα 😄
Shuffled: α😄άλλ Εδ

Truncate string containing emoji or unicode characters at word or character boundaries

How can I truncate a string at a given length without annihilating a unicode character that might be smack in the middle of my length? How can one determine the index of the beginning of a unicode character in a string so that I can avoid creating ugly strings. The square with half of an A visible is the location of another emoji character which has been truncated.
-(NSMutableAttributedString*)constructStatusAttributedStringWithRange:(CFRange)range
NSString *original = [_postDictionay objectForKey:#"message"];
NSMutableString *truncated = [NSMutableString string];
NSArray *components = [original componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
for(int x=0; x<[components count]; x++)
{
//If the truncated string is still shorter then the range desired. (leave space for ...)
if([truncated length]+[[components objectAtIndex:x] length]<range.length-3)
{
//Just checking if its the first word
if([truncated length]==0 && x==0)
{
//start off the string
[truncated appendString:[components objectAtIndex:0]];
}
else
{
//append a new word to the string
[truncated appendFormat:#" %#",[components objectAtIndex:x]];
}
}
else
{
x=[components count];
}
}
if([truncated length]==0 || [truncated length]< range.length-20)
{
truncated = [NSMutableString stringWithString:[original substringWithRange:NSMakeRange(range.location, range.length-3)]];
}
[truncated appendString:#"..."];
NSMutableAttributedString *statusString = [[NSMutableAttributedString alloc]initWithString:truncated];
[statusString addAttribute:(id)kCTFontAttributeName value:[StyleSingleton streamStatusFont] range:NSMakeRange(0, [statusString length])];
[statusString addAttribute:(id)kCTForegroundColorAttributeName value:(id)[StyleSingleton streamStatusColor].CGColor range:NSMakeRange(0, [statusString length])];
return statusString;
}
UPDATE Thanks to the answer, was able to use one simple function for my needs!
-(NSMutableAttributedString*)constructStatusAttributedStringWithRange:(CFRange)range
{
NSString *original = [_postDictionay objectForKey:#"message"];
NSMutableString *truncated = [NSMutableString stringWithString:[original substringWithRange:[original rangeOfComposedCharacterSequencesForRange:NSMakeRange(range.location, range.length-3)]]];
[truncated appendString:#"..."];
NSMutableAttributedString *statusString = [[NSMutableAttributedString alloc]initWithString:truncated];
[statusString addAttribute:(id)kCTFontAttributeName value:[StyleSingleton streamStatusFont] range:NSMakeRange(0, [statusString length])];
[statusString addAttribute:(id)kCTForegroundColorAttributeName value:(id)[StyleSingleton streamStatusColor].CGColor range:NSMakeRange(0, [statusString length])];
return statusString;
}
NSString has a method rangeOfComposedCharacterSequencesForRange that you can use to find the enclosing range in the string that contains only complete composed characters. For example
NSString *s = #"😄";
NSRange r = [s rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 1)];
gives the range { 0, 2 } because the Emoji character is stored as two UTF-16 characters (surrogate pair) in the string.
Remark: You could also check if you can simplify your first loop by using
enumerateSubstringsInRange:options:usingBlock
with the NSStringEnumerationByWords option.
"truncate a string at a given length" <-- Do you mean length as in byte length or length as in number of characters? If the latter, then a simple substringToIndex: will suffice (check the bounds first though). If the former, then I'm afraid you'll have to do something like:
NSString *TruncateString(NSString *original, NSUInteger maxBytesToRead, NSStringEncoding targetEncoding) {
NSMutableString *truncatedString = [NSMutableString string];
NSUInteger bytesRead = 0;
NSUInteger charIdx = 0;
while (bytesRead < maxBytesToRead && charIdx < [original length]) {
NSString *character = [original substringWithRange:NSMakeRange(charIdx++, 1)];
bytesRead += [character lengthOfBytesUsingEncoding:targetEncoding];
if (bytesRead <= maxBytesToRead)
[truncatedString appendString:character];
}
return truncatedString;
}
EDIT: Your code can be rewritten as follows:
NSString *original = [_postDictionay objectForKey:#"message"];
NSArray *characters = [[original componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF != ''"]];
NSArray *truncatedCharacters = [characters subarrayWithRange:range];
NSString *truncated = [NSString stringWithFormat:#"%#...", [truncatedCharacters componentsJoinedByString:#" "]];

NSString replace unicode characters

I'w working with a server and I have to download text to my iOS application. Only problem : all characters like "é à ç" are replaced by "\U008" for example. Is there a way to fix this problem, to replace this code by the right character ?
Try to parse the received text (textToParse variable) with this one:
NSString *encodedString = textToParse;
NSString *decodedString = [NSString stringWithUTF8String:[encodedString cStringUsingEncoding:[NSString defaultCStringEncoding]]];
I tested some encodings and NSMacOSRomanStringEncoding fit well.
My test was:
NSString *encodedString = [NSString stringWithCString:"Você realmente deseja sair da área restrita" encoding:NSMacOSRomanStringEncoding];
Remember that the message has to be a C-string ("string") and not an NSString(#"string")
You can get character buffer and validate each character like so:
- (NSString *) removeUnicode:(NSString *) unicodeString {
NSUInteger len = [unicodeString length];
unichar buffer[len+1];
[unicodeString getCharacters:buffer range:NSMakeRange(0, len)];
unichar okBuffer[len+1];
int index = 0;
for(int i = 0; i < len; i++) {
if(buffer[i] < 128) {
okBuffer[index] = buffer[i];
index = index + 1;
}
}
NSString *removedUnicode = [[NSString alloc] initWithCharacters:okBuffer length:index];
return removedUnicode;
}
or you can use this sample:
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:[NSCharacterSet alphanumericCharacterSet]] invertedSet];
stringWithOutUnicode = [[stringWithUnicode componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
and you can create your own valid character set and get not allowed characters
NSString *allowedCharacters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString: allowedCharacters] invertedSet];

Resources