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

I have a NSString with hex string like "68656C6C6F" which means "hello".
Now I want to convert the hex string into another NSString object which shows "hello". How to do that ?

I am sure there are far better, cleverer ways to do this, but this solution does actually work.
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 should do it:
- (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;
}

+(NSString*)intToHexString:(NSInteger)value
{
return [[NSString alloc] initWithFormat:#"%lX", value];
}

extension String {
func hexToString()-> String {
var newString = ""
var i = 0
while i < self.count {
let hexChar = (self as NSString).substring(with: NSRange(location: i, length: 2))
if let byte = Int8(hexChar, radix: 16) {
if (byte != 0) {
newString += String(format: "%c", byte)
}
}
i += 2
}
return newString
}
}

I think the people advising initWithFormat is the best answer as it's objective-C rather than a mix of ObjC, C.. (although the sample code is a bit terse).. I did the following
unsigned int resInit = 0x1013;
if (0 != resInit)
{
NSString *s = [[NSString alloc] initWithFormat:#"Error code 0x%lX", resInit];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Initialised failed"
message:s
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
[s release];
}

Related

Reverse strings in array objectivec [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reverse NSString text
i am new on objectovec. i have a array having strings. how to reverse each string?
which method of NSArray and NSstring will help me out?
i want reversed string in the array.
thanks
Create a method that will return a reversed string.
-(NSString *)reverseString:(NSString *)string{
NSString *reverseString=[NSString new];
for (NSInteger i=string.length-1; i>-1; i--) {
reverseString=[reverseString stringByAppendingFormat:#"%c",[string characterAtIndex:i]];
}
return reverseString;
}
In your any of the method :
NSMutableArray *names=[NSMutableArray arrayWithObjects:#"anoop",#"johnson",#"wasim",nil];
for (NSInteger i=0; i<names.count; i++) {
names[i]=[self reverseString:names[i]];
}
NSLog(#"%#",names);
Hope this help
NSString *str=textEntered.text;//
NSMutableArray *temp=[[NSMutableArray alloc] init];
for(int i=0;i<[str length];i++)
{
[temp addObject:[NSString stringWithFormat:#"%c",[str characterAtIndex:i]]];
}
temp = [NSMutableArray arrayWithArray:[[temp reverseObjectEnumerator] allObjects]];
NSString *reverseString=#"";
for(int i=0;i<[temp count];i++)
{
reverseString=[NSString stringWithFormat:#"%#%#",reverseString,[temp objectAtIndex:i]];
}
NSLog(#"%#",reverseString);
NSString *str=textEntered.text;//
NSMutableArray *temp=[[NSMutableArray alloc] init];
for(int i=0;i<[str length];i++)
{
[temp addObject:[NSString stringWithFormat:#"%c",[str characterAtIndex:i]]];
}
temp = [NSMutableArray arrayWithArray:[[temp reverseObjectEnumerator] allObjects]];
NSString *reverseString=#"";
for(int i=0;i<[temp count];i++)
{
reverseString=[NSString stringWithFormat:#"%#%#",reverseString,[temp objectAtIndex:i]];
}
NSLog(#"%#",reverseString);
AnOther way for revers string NSStringEnumerationOptions
- (NSString *)reverseString:(NSString *)string {
NSMutableString *reversedString = [[NSMutableString alloc] init];
NSRange fullRange = [string rangeOfString:string];
NSStringEnumerationOptions enumerationOptions = (NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences);
[string enumerateSubstringsInRange:fullRange options:enumerationOptions usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[reversedString appendString:substring];
}];
return reversedString;
}
Use
unichar c[yourstring.Length];
NSRange raneg={0,yourstring.Length};
[yourstring getCharacters:c range:raneg];
//c will be an array of your string do what ever you wish
Use this one to reverse your string and then store back to your array at same index.
-(NSString*)reverseString:(NSString*)string {
NSMutableString *reversedString;
int length = [string length];
reversedString = [NSMutableString stringWithCapacity:length];
while (length--) {
[reversedString appendFormat:#"%c", [string characterAtIndex:length]];
}
return reversedString;
}
But if you have mutable string then you can create a category
#interface NSMutableString (Reverse)
- (void)reverseString;
#end
#implementation NSMutableString (Reverse)
- (void)reverseString {
for (int i = 0; i < self.length/2; i++) {
int l = self.length - 1 - i;
NSRange iRange = NSMakeRange(i, 1);
NSRange lRange = NSMakeRange(l, 1);
NSString *iStr = [self substringWithRange:iRange];
NSString *lStr = [self substringWithRange:lRange];
[self replaceCharactersInRange:iRange withString:lStr];
[self replaceCharactersInRange:lRange withString:iStr];
}
}
#end
And then you can use this category method like this
NSArray *arr = [NSArray arrayWithObjects:[#"hello" mutableCopy], [#"Do it now" mutableCopy], [#"Test string, 123 123" mutableCopy], nil];
NSLog(#"%#",arr);
[arr makeObjectsPerformSelector:#selector(reverseString)];
NSLog(#"%#",arr);

How to random sort a NSString

NSMutableString *str =#"abcdefg123";
I want random the every character to a new String like this #"f1ad2g3be2".
NSMutableString *str1 = [[NSMutableString alloc]initWithString:str];
NSMutableString *str2 = [[NSMutableString alloc] init];
while ([str1 length] > 0) {
int i = arc4random() % [str1 length];
NSRange range = NSMakeRange(i,1);
NSString *sub = [str1 substringWithRange:range];
[str2 appendString:sub];
[str1 replaceOccurrencesOfString:sub withString:#"" options:nil range:range];
}
[str1 release];
str2 is what u want
Quite simple. First you must break up the characters into an array to work with. Then you swap the letters X many times, I choose to do this so every character will be swapped
NSString *str =#"abcdefg123";
int length = str.length;
NSMutableArray *letters = [[NSMutableArray alloc] init];
for (int i = 0; i< length; i++) {
NSString *letter = [NSString stringWithFormat:#"%c", [str characterAtIndex:i]];
[letters addObject:letter];
}
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
NSLog(#"Value is : %i", value);
[letters exchangeObjectAtIndex:i withObjectAtIndex:value];
}
NSString *results = [letters componentsJoinedByString:#""];
NSLog(#"The string before : %#", str);
NSLog(#"This is the string now : %#", results);

Change the position of character in string

I have a two string like "SANFRANSICO" and "CHICAGO"
Now i want to make it like the string is in reverse but in a single string like "OOCGIASCNIAHRCFNAS"
I have done code but it gives me wrong result
check out my code
- (NSString *)changeString1:(NSString *)string string2:(NSString *)string2{
int first = [string length];
int second = [string2 length];
int total = first+second;
NSMutableString *str = [[NSMutableString alloc] init];
string = [self reverseString:string];
string2 = [self reverseString:string2];
for (int i=0; i<total+1; i++)
{
if (i%2==1) {
int j = i/2;
if(j < second){
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j+1]];
NSLog(#"222 %d %#",j+1, ichar );
[str appendString:ichar];
check = YES;
}
}
else {
int j = i/2;
if(check == YES){
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j]];
NSLog(#"1111 %d %#",j, ichar );
[str appendString:ichar];
}
}
}
return str;
}
I found the answer very soon after post this question sorry for posting this question
check out my answer
- (NSString *)changeString1:(NSString *)string string2:(NSMutableString *)string2{
int first = [string length];
int second = [string2 length];
string = [self reverseString:string];
string2 = [self reverseString:string2];
for(int i =second; i<first; i ++){
[string2 appendString:#" "];
}
int total = first*2;
NSMutableString *str = [[NSMutableString alloc] init];
for (int i=0; i<total; i++)
{
if (i%2==1) {
int j = i/2;
if(j < second){
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
}
else {
int j = i/2;
if(j < first){
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j]];
[str appendString:ichar];
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
}
}
NSLog(#"str %#", str);
return str;
}

nsstring replace string in range

I have a string with certain pattern. I need to search for the pattern and replace the string inside that pattern. For eg :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSString *result = nil;
// Determine "{" location
NSRange startRange = [string rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [string length] - endRange.location;
endRange = [string rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
result = [string substringWithRange:startRange];
}
}
Here I am able to extract the first substring that is between "{ }" ie - "Hello" but I also need to continue the check and want to extract other strings.
Try this one:
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
//NSString *result = nil;
// Determine "{" location
NSArray *array=[string componentsSeparatedByString:#"{"];
for(NSString *str in array){
NSString *newString=[[str componentsSeparatedByString:#"}"] objectAtIndex:0];
NSLog(#"%#",newString);
}
try this :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSMutableString *result = [[NSMutableString alloc] init];
NSArray *tempArray = [[string componentsSeparatedByString:#" "] mutableCopy];
for (int i=0; i < [tempArray count]; i++)
{
NSString *tempStr = [tempArray objectAtIndex:i];
NSRange startRange = [tempStr rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [tempStr length] - endRange.location;
endRange = [tempStr rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
//result = [tempStr substringWithRange:startRange];
[result appendString:[NSString stringWithFormat:#"%# ",[tempStr substringWithRange:startRange]]];
NSLog(#"%# ",result);
}
}
}
Take care for release for tempArray and result
I happen to have this code lying around. I think it does exactly what you want. I implemented it as a category on NSString. You use it like this:
NSString *template = #"{Hello} ({World}) ({How}) etc etc";
NSDictionary *vars = [NSDictionary dictionaryWithObjectsAndKeys:
#"Bonjour", #"Hello",
#"Planet Earth", #"World",
#"Como", #"How",
// etc.
nil];
NSString *expandedString = [template stringByExpandingTemplateWithVariables:vars];
// expandedString is #"Bonjour (Planet Earth) (Como) etc etc"
Here's the code.
File NSString+TemplateExpansion.h
#import <Foundation/Foundation.h>
#interface NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary;
#end
File NSString+TemplateExpansion.m
#import "NSString+TemplateExpansion.h"
#implementation NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary
{
NSUInteger myLength = self.length;
NSMutableString *result = [NSMutableString stringWithCapacity:myLength];
NSRange remainingRange = NSMakeRange(0, myLength);
while (remainingRange.length > 0) {
NSRange leftBraceRange = [self rangeOfString:#"{" options:0 range:remainingRange];
if (leftBraceRange.location == NSNotFound)
break;
NSRange afterLeftBraceRange = NSMakeRange(NSMaxRange(leftBraceRange), myLength - NSMaxRange(leftBraceRange));
NSRange rightBraceRange = [self rangeOfString:#"}" options:0 range:afterLeftBraceRange];
if (rightBraceRange.location == NSNotFound)
break;
NSRange beforeLeftBraceRange = NSMakeRange(remainingRange.location, leftBraceRange.location - remainingRange.location);
[result appendString:[self substringWithRange:beforeLeftBraceRange]];
remainingRange = NSMakeRange(NSMaxRange(rightBraceRange), myLength - NSMaxRange(rightBraceRange));
NSRange keyRange = NSMakeRange(NSMaxRange(leftBraceRange), rightBraceRange.location - NSMaxRange(leftBraceRange));
NSString *key = [self substringWithRange:keyRange];
NSString *value = [dictionary objectForKey:key];
if (value)
[result appendString:value];
}
[result appendString:[self substringWithRange:remainingRange]];
return result;
}
#end

Subtracting 2 strings

I have a string say for example #"012" and I have another string #"02". How can I extract the difference of the 2 strings in iPhone Objective-C. I just need to remove the existence of the characters in the 2nd string from the first string.The answer would be "1".
Even shorter:
NSString* s1 = #"012";
NSString* s2 = #"02";
NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:s2];
NSString * final = [[s1 componentsSeparatedByCharactersInSet:set] componentsJoinedByString:#""];
NSLog(#"Final: %#", final);
This preserves the order of the characters in the original string.
You could do something like this;
NSString *s1 = #"012";
NSString *s2 = #"02";
NSCharacterSet *charactersToRemove;
charactersToRemove = [NSCharacterSet characterSetWithCharactersInString:s2];
NSMutableString *result = [NSMutableString stringWithCapacity:[s1 length]];
for (NSUInteger i = 0; i < [s1 length]; i++) {
unichar c = [s1 characterAtIndex:i];
if (![charactersToRemove characterIsMember:c]) {
[result appendFormat:#"%C", c];
}
}
// if memory is an issue:
result = [[result copy] autorelease];
Disclaimer: I typed this into the browser, and haven't tested any of this.
You're trying to do a set operation, so use sets.
{
NSString* s1 = #"012";
NSString* s2 = #"02";
NSMutableSet* set1 = [NSMutableSet set];
NSMutableSet* set2 = [NSMutableSet set];
for(NSUInteger i = 0; i < [s1 length]; ++i)
{
[set1 addObject:[s1 substringWithRange:NSMakeRange(i, 1)]];
}
for(NSUInteger i = 0; i < [s2 length]; ++i)
{
[set2 addObject:[s2 substringWithRange:NSMakeRange(i, 1)]];
}
[set1 minusSet:set2];
NSLog(#"set1: %#", set1);
// To get a single NSString back from the set:
NSMutableString* result = [NSMutableString string];
for(NSString* piece in set1)
{
[result appendString:piece];
}
NSLog(#"result: %#", result);
}
I simply used "componentsSeparatedByString"
NSString *s1 = #"abc";
NSString *s2 = #"abcdef";
//s2 - s1
NSString * final = [[s2 componentsSeparatedByString:s1] componentsJoinedByString:#""];