Objective-C Iterating through an NSString to get characters - objective-c

I have this function:
void myFunc(NSString* data) {
NSMutableArray *instrs = [[NSMutableArray alloc] initWithCapacity:[data length]];
for (int i=0; i < [data length]; i++) {
unichar c = [data characterAtIndex:i];
[instrs addObject:c];
}
NSEnumerator *e = [instrs objectEnumerator];
id inst;
while (inst = [e nextObject]) {
NSLog("%i\n", inst);
}
}
I think it fails at [instrs addObject:c]. It's purpose is to iterate through the hexadecimal numbers of an NSString. What causes this code to fail?

A unichar is not an object; it's an integer type.
NSMutableArray can only hold objects.
If you really want to put it into an NSMutableArray, you could wrap the integer value in an NSNumber object: [instrs addObject:[NSNumber numberWithInt:c]];
But, what's the point of stuffing the values into an array in the first place? You know how to iterate through the string and get the characters, why put them into an array just to iterate through them again?
Also note that:
the "%i" NSLog format expects an integer; you can't pass it an object
for hexadecimal output, you want "%x", not "%i"

If the function is only meant to display the characters as hexadecimal values, you could use:
void myFunc(NSString* data)
{
NSUInteger len = [data length];
unichar *buffer = calloc(len, sizeof(unichar));
if (!buffer) return;
[data getCharacters:buffer range:NSMakeRange(0, len)];
for (NSUInteger i = 0; i < len; i++)
NSLog(#"%04x", (unsigned) buffer[i]);
free(buffer);
}
This is just a little bit more efficient than your approach (also, in your approach you never release the instrs array, so it will leak in a non-garbage-collected environment).
If the string contains hexadecimal numbers, then you will want to repeatedly use an NSScanner's scanHexInt: method until it returns NO.
void myFunc(NSString* data)
{
NSScanner *scanner = [[NSScanner alloc] initWithString:data];
unsigned number;
while ([scanner scanHexInt:&number])
NSLog(#"%u", number);
[scanner release];
}

Related

divide string into characters

I have an NSString *titleName which changes according to an if statement. So the length (number of characters) in the string changes. I would like to divide titleName into a MutableArray of separate strings consisting of its individual characters. I would then like to use these separate strings as the text in different UILabels. I am not sure as how to go about this.
Through some research I have tried to create the NSMutable array like this
NSMutableArray *letterArray = substringWithRange:((i = 0);i<[titleName2 length];i++));
but this gives me an error Use of undeclared identifier 'substringWithRange.
Can someone help me.
I decided to use componentsSeparatedByString instead and just created my various strings with a , between each letter. Thanks for anybody's thoughts though.
The code you pasted is not valid objective-C.
To keep the same algorithm you should write something like :
NSMutableArray *letterArray = [NSMutableArray array];
NSUInteger length = [titleName2 length];
for (NSUInteger i = 0; i < length; ++i) {
[letterArray addObject:[titleName2 substringWithRange:NSMakeRange(i, 1)]];
}
It's probably much "cheaper" to hold a C-array of unichar characters that make-up the string. It will also be quicker to create:
NSString *input = #"How now brown cow?";
unichar chars[[input length]];
for (NSInteger i = 0; i < [input length]; i++)
chars[i] = [input characterAtIndex:i];
Alternatively you could use malloc() to create the C-array:
NSString *input = #"How now brown cow?";
unichar *chars = (unichar *)malloc([input length]);
for (NSInteger i = 0; i < [input length]; i++)
chars[i] = [input characterAtIndex:i];
and then use free(), later, to, err, free the memory:
free(chars);
Cheaper still, would be to not split-up the string at all...
Try this below code
NSMutableArray *letterArray = [NSMutableArray array];
for (int i = 0;i<[titleName2 length];i++)
{
[letterArray addObject: [titleName2 substringWithRange:NSMakeRange(i,1)]];
}
DLog(#"%#", letterArray);
Other option to get characters of string
NSMutableArray *letterArray = [NSMutableArray array];
for (int i=0; i < [titleName2 length]; i++)
{
[letterArray addObject:[NSString stringWithFormat:#"%c", [titleName2 characterAtIndex:i]]];
}
DLog(#"characters - %#", letterArray);

Sort characters in NSString into alphabetical order

I'm trying to re-arrange words into alphabetical order. For example, tomato would become amoott, or stack would become ackst.
I've found some methods to do this in C with char arrays, but I'm having issues getting that to work within the confines of the NSString object.
Is there an easier way to do it within the NSString object itself?
You could store each of the string's characters into an NSArray of NSNumber objects and then sort that. Seems a bit expensive, so I would perhaps just use qsort() instead.
Here it's provided as an Objective-C category (untested):
NSString+SortExtension.h:
#import <Foundation/Foundation.h>
#interface NSString (SortExtension)
- (NSString *)sorted;
#end
NSString+SortExtension.m:
#import "NSString+SortExtension.h"
#implementation NSString (SortExtension)
- (NSString *)sorted
{
// init
NSUInteger length = [self length];
unichar *chars = (unichar *)malloc(sizeof(unichar) * length);
// extract
[self getCharacters:chars range:NSMakeRange(0, length)];
// sort (for western alphabets only)
qsort_b(chars, length, sizeof(unichar), ^(const void *l, const void *r) {
unichar left = *(unichar *)l;
unichar right = *(unichar *)r;
return (int)(left - right);
});
// recreate
NSString *sorted = [NSString stringWithCharacters:chars length:length];
// clean-up
free(chars);
return sorted;
}
#end
I think separate the string to an array of string(each string in the array contains only one char from the original string). Then sort the array will be OK. This is not efficient but is enough when the string is not very long. I've tested the code.
NSString *str = #"stack";
NSMutableArray *charArray = [NSMutableArray arrayWithCapacity:str.length];
for (int i=0; i<str.length; ++i) {
NSString *charStr = [str substringWithRange:NSMakeRange(i, 1)];
[charArray addObject:charStr];
}
NSString *sortedStr = [[charArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] componentsJoinedByString:#""];
// --------- Function To Make an Array from String
NSArray *makeArrayFromString(NSString *my_string) {
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i < my_string.length; i ++) {
[array addObject:[NSString stringWithFormat:#"%c", [my_string characterAtIndex:i]]];
}
return array;
}
// --------- Function To Sort Array
NSArray *sortArrayAlphabetically(NSArray *my_array) {
my_array= [my_array sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
return my_array;
}
// --------- Function Combine Array To Single String
NSString *combineArrayIntoString(NSArray *my_array) {
NSString * combinedString = [[my_array valueForKey:#"description"] componentsJoinedByString:#""];
return combinedString;
}
// Now you can call the functions as in below where string_to_arrange is your string
NSArray *blowUpArray;
blowUpArray = makeArrayFromString(string_to_arrange);
blowUpArray = sortArrayAlphabetically(blowUpArray);
NSString *arrayToString= combineArrayIntoString(blowUpArray);
NSLog(#"arranged string = %#",arrayToString);
Just another example using NSMutableString and sortUsingComparator:
NSMutableString *mutableString = [[NSMutableString alloc] initWithString:#"tomat"];
[mutableString appendString:#"o"];
NSLog(#"Orignal string: %#", mutableString);
NSMutableArray *charArray = [NSMutableArray array];
for (int i = 0; i < mutableString.length; ++i) {
[charArray addObject:[NSNumber numberWithChar:[mutableString characterAtIndex:i]]];
}
[charArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
if ([obj1 charValue] < [obj2 charValue]) return NSOrderedAscending;
return NSOrderedDescending;
}];
[mutableString setString:#""];
for (int i = 0; i < charArray.count; ++i) {
[mutableString appendFormat:#"%c", [charArray[i] charValue]];
}
NSLog(#"Sorted string: %#", mutableString);
Output:
Orignal string: tomato
Sorted string: amoott

string tokenizer in ios

I like to tokenize a string to characters and store the tokens in a string array. I am trying to use following code which is not working as I am using C notation to access the array. What needs to be changed in place of travel path[i]?
NSArray *tokanizedTravelPath= [[NSArray alloc]init];
for (int i=0; [travelPath length]; i++) {
tokanizedTravelPath[i]= [travelPath characterAtIndex:i];
You can't store unichars in an NSArray*. What exactly are you trying to accomplish? An NSString* is already a great representation for a collection of unichars, and you already have one of those.
You need a NSMutableArray to set every element of the array (otherwise you can't change its objects).Also, you can only insert objects in the array, so you can:
- Insert a NSString containing the character;
- Use a C-style array instead.
This is how to do with the NSMutableArray:
NSMutableArray *tokanizedTravelPath= [[NSMutableArray alloc]init];
for (int i=0; i<[travelPath length]; i++)
{
[tokanizedTravelPath insertObject: [NSString stringWithFormat: #"%c", [travelPath characterAtIndex:i]] atIndex: i];
}
I count 3 errors in your code, I explain them at the end of my answer.
First I want to show you a better approach to split a sting into it characters.
While I agree with Kevin that an NSString is a great representation of unicode characters already, you can use this block-based code to split it into substrings and save it to an array.
Form the docs:
enumerateSubstringsInRange:options:usingBlock:
Enumerates the
substrings of the specified type in the specified range of the string.
NSString *hwlloWord = #"Hello World";
NSMutableArray *charArray = [NSMutableArray array];
[hwlloWord enumerateSubstringsInRange:NSMakeRange(0, [hwlloWord length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring,
NSRange substringRange,
NSRange enclosingRange,
BOOL *stop)
{
[charArray addObject:substring];
}];
NSLog(#"%#", charArray);
Output:
(
H,
e,
l,
l,
o,
" ",
W,
o,
r,
l,
d
)
But actually your problems are of another nature:
An NSArray is immutable. Once instantiated, it cannot be altered. For mutable array, you use the NSArray subclass NSMutableArray.
Also, characterAtIndex does not return an object, but a primitive type — but those can't be saved to an NSArray. You have to wrap it into an NSString or some other representation.
You could use substringWithRange instead.
NSMutableArray *tokanizedTravelPath= [NSMutableArray array];
for (int i=0; i < [hwlloWord length]; ++i) {
NSLog(#"%#",[hwlloWord substringWithRange:NSMakeRange(i, 1)]);
[tokanizedTravelPath addObject:[hwlloWord substringWithRange:NSMakeRange(i, 1)]];
}
Also your for-loop is wrong, the for-loop condition is not correct. it must be for (int i=0; i < [travelPath length]; i++)

XOR'ing two hex values stored as an NSString?

here is yet another silly question from me!
NSString *hex1 = #"50be4f3de4";
NSString *hex2 = #"30bf69a299";
/* some stuff like result = hex1^hex2; */
NSString *result = #"6001269f7d";
I have a hex value as a string, stored in two diff. variables. i need to Xor them and the result should be in another string variables?
i tried them by converting string --> NSData --> bytes array --> xor'ing them ...but i have no success.....
thank you in advance...
You have to convert every character to Base16(for hexadecimal) format first.Then you should proceed with XORing those characters.You can use the strtol() function to achieve this purpose.
NSString *hex1 = #"50be4f3de4";
NSString *hex2 = #"30bf69a299";
NSMutableArray *hexArray1 = [self splitStringIntoChars:hex1];
NSMutableArray *hexArray2 = [self splitStringIntoChars:hex2];
NSMutableString *str = [NSMutableString new];
for (int i=0; i<[hexArray1 count]; i++ )
{
/*Convert to base 16*/
int a=(unsigned char)strtol([[hexArray1 objectAtIndex:i] UTF8String], NULL, 16);
int b=(unsigned char)strtol([[hexArray2 objectAtIndex:i] UTF8String], NULL, 16);
char encrypted = a ^ b;
NSLog(#"%x",encrypted);
[str appendFormat:#"%x",encrypted];
}
NSLog(#"%#",str);
Utility method that i used to split characters of the string
-(NSMutableArray*)splitStringIntoChars:(NSString*)argStr{
NSMutableArray *characters = [[NSMutableArray alloc]
initWithCapacity:[argStr length]];
for (int i=0; i < [argStr length]; i++)
{
NSString *ichar = [NSString stringWithFormat:#"%c", [argStr characterAtIndex:i ]];
[characters addObject:ichar];
}
return characters;
}
Hope it helps!!

Storing data in string into an integer array

I have some data into a string and I wish to store that data in an integer array... Below is the code.
int valMines[256];
// 'b' is NSString with 256 values in it.
for(int i=0; i<[b length]; i++){
valMines[i] = [NSString stringWithFormat:#"%d", [b characterAtIndex:i]];
NSLog(#"valMines1 is %#", valMines[i]);
}
I am getting a warning and due to that my application is not getting loaded:
Assignment makes integer from pointer without a cast.
Please help
Your valMins is an integer array and you are assigning NSString to it. Probably you are looking something like this:
unichar valMines[256]; // make it unichar instead of int
// 'b' is NSString with 256 values in it.
for(int i=0; i<[b length]; i++){
valMines[i] = [b characterAtIndex:i]; // get and store the unichar
NSLog(#"valMines1 is %d", valMines[i]); // format specifier is %d, not %#
}