NSString to NSArray and editing every object - objective-c

I have an NSString filled with objects seperated by a comma
NSString *string = #"1,2,3,4";
I need to seperate those numbers and store then into an array while editing them, the result should be
element 0 = 0:1,
element 1 = 1:2,
element 2 = 2:3,
element 3 = 3:4.
How can i add those to my objects in the string ??
Thanks.
P.S : EDIT
I already did that :
NSString *string = #"1,2,3,4";
NSArray *array = [string componentsSeparatedByString:#","];
[array objectAtIndex:0];//1
[array objectAtIndex:1];//2
[array objectAtIndex:2];//3
[array objectAtIndex:3];//4
I need the result to be :
[array objectAtIndex:0];//0:1
[array objectAtIndex:1];//1:2
[array objectAtIndex:2];//2:3
[array objectAtIndex:3];//3:4

In lieu of a built in map function (yey for Swift) you would have to iterate over the array and construct a new array containing the desired strings:
NSString *string = #"1,2,3,4";
NSArray *array = [string componentsSeparatedByString:#","];
NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:array.count];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[newArray addObject:[NSString stringWithFormat:#"%lu:%#", (unsigned long)idx, obj]];
}];

The first thing you need to do is separate the string into an array of component parts - NSString has a handy method for that : '-componentsSeparatedByString'. Code should be something like this :
NSArray *components = [string componentsSeparatedByString:#","];
So that gives you 4 NSString objects in your array. You could then iterate through them to make compound objects in your array, though you arent exactly clear how or why you need those. Maybe something like this :
NSMutableArray *resultItems = [NSMutableArray array];
for (NSString *item in components)
{
NSString *newItem = [NSString stringWithFormat:#"%#: ... create your new item", item];
[resultItems addObject:newItem];
}

How about this?
NSString *string = #"1,2,3,4";
NSArray *myOldarray = [string componentsSeparatedByString:#","];
NSMutableArray *myNewArray = [[NSMutableArray alloc] init];
for (int i=0;i<myOldarray.count;i++) {
[myNewArray addObject:[NSString stringWithFormat:#"%#:%d", [myOldarray objectAtIndex:i], ([[myOldarray objectAtIndex:i] intValue]+1)]];
}
// now you have myNewArray what you want.
This is with consideration that in array you want number:number+1

Related

How to separate NSArray values?

NSArray has 3 values
#[#"addd:etyrhetwrwr", #"fdfdd:jjjjhhhh", #"fsuy:jjhwgggggg"]
And I want to put this array into the UILabel with word wrap.
So when I run, it should show like this in label.
addd:etyrhetwrwr
fdfdd:jjjjhhhh
fsuy:jjhwgggggg
But I can't separate this NSArray. How can I do that?
NSArray *myArray = #[#"addd:etyrhetwrwr", #"fdfdd:jjjjhhhh", #"fsuy:jjhwgggggg"];
NSString *labelString = [myArray componentsJoinedByString:#"\n"];
Then use the labelString to set your label text property.
Try This
NSArray *yourArray = #[#"addd:etyrhetwrwr", #"fdfdd:jjjjhhhh", #"fsuy:jjhwgggggg"];
NSString *string = [myArray componentsJoinedByString:#"\n"];
[yourLabel setText:string];
You can separate NSArray in UILabel by
NSArray myArr = #[#"addd:etyrhetwrwr", #"fdfdd:jjjjhhhh", #"fsuy:jjhwgggggg"];
NSString strLabel = [myArr string:#"\n"];
try this code
NSArray *array = [[NSArray alloc] initWithObjects:#"adad",#"fgfdgdfg",#"sddgfs", nil];
NSMutableString *strFinalData = [[NSMutableString alloc] init];
for (int i=0; i<[array count]; i++)
{
[strFinalData appendFormat:#"%# ",[array objectAtIndex:i]];
}
NSLog(#"Final String: %#",strFinalData);
Now set yourLabel.text = strFinalData;

Is there a simple way to split a NSString into an array of characters?

Is there a simple way to split a NSString into an array of characters? It would actually be best if the resulting type were a collection of NSString's themselves, just one character each.
Yes, I know I can do this in a loop, but I'm wondering if there is a faster way to do this with any existing methods or functions the way you can with LINQ in C#.
e.g.
// I have this...
NSString * fooString = #"Hello";
// And want this...
NSArray * fooChars; // <-- Contains the NSStrings, #"H", #"e", #"l", #"l" and #"o"
You could do something like this (if you want to use enumerators)
NSString *fooString = #"Hello";
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[fooString length]];
[fooString enumerateSubstringsInRange:NSMakeRange(0, fooString.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[characters addObject:substring];
}];
And if you really wanted it in an NSArray finally
NSArray *fooChars = [NSArray arrayWithArray:characters];
Be sure to care about that some characters like emoji and others may span a longer range than just one index.
Here's a category method for NSString
#implementation (SplitString)
- (NSArray *)splitString
{
NSUInteger index = 0;
NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.length];
while (index < self.length) {
NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:index];
NSString *substring = [self substringWithRange:range];
[array addObject:substring];
index = range.location + range.length;
}
return array;
}
#end
convert it to NSData the [data bytes] will have a C string in the encoding that you pick [data length] bytes long.
Try this
NSMutableArray *array = [NSMutableArray array];
NSString *str = #"Hello";
for (int i = 0; i < [str length]; i++) {
NSString *ch = [str substringWithRange:NSMakeRange(i, 1)];
[array addObject:ch];
}

Searching NSArray using suffixes

I have a word list stored in an NSArray, I want to find all the words in it with the ending 'ing'.
Could someone please provide me with some sample/pseudo code.
Use NSPredicate to filter NSArrays.
NSArray *array = #[#"test", #"testing", #"check", #"checking"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF ENDSWITH 'ing'"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
Let's say you have an array defined:
NSArray *wordList = // you have the contents defined properly
Then you can enumerate the array using a block
// This array will hold the results.
NSMutableArray *resultArray = [NSMutableArray new];
// Enumerate the wordlist with a block
[wordlist enumerateObjectsUsingBlock:(id obj, NSUInteger idx, BOOL *stop) {
if ([obj hasSuffix:#"ing"]) {
// Add the word to the result list
[result addObject:obj];
}
}];
// resultArray now has the words ending in "ing"
(I am using ARC in this code block)
I am giving an example using blocks because its gives you more options should you need them, and it's a more modern approach to enumerating collections. You could also do this with a concurrent enumeration and get some performance benefits as well.
Just loop through it and check the suffixes like that:
for (NSString *myString in myArray) {
if ([myString hasSuffix:#"ing"]){
// do something with myString which ends with "ing"
}
}
NSMutableArray *results = [[NSMutableArray alloc] init];
// assuming your array of words is called array:
for (int i = 0; i < [array count]; i++)
{
NSString *word = [array objectAtIndex: i];
if ([word hasSuffix: #"ing"])
[results addObject: word];
}
// do some processing
[results release]; // if you're not using ARC yet.
Typed from scratch, should work :)

sum quantity of dictionaries in array

I have a NSArray containing a list of NSDictionary. Like:
NSArray *array = ...;
NSDictionary *item = [array objectAtIndex:0];
NSLog (#"quantity: %#", [item objectForKey: #"quantity"]);
How can I sum all the quantities contained in all dictionaries of the array?
I think you can try KVC
NSMutableArray *goods = [[NSMutableArray alloc] init];
NSString *key = #"quantity";
[goods addObject:#{key:#(1)}];
[goods addObject:#{key:#(2)}];
[goods addObject:#{key:#(3)}];
NSNumber *sum = [goods valueForKeyPath:#"#sum.quantity"];
NSLog(#"sum = %#", sum);
If you call valueForKey: on an array it gives you an array of all the values for that key, so [array valueForKey:#"quantity"] will give you an array which you can loop over and sum all the values.
NSMutableArray *quantityArray = [item objectForKey: #"quantity"];
int total =0;
for(int i=0;i<[quantityArray count];i++)
{
total+= [quantityArray objectAtIndex:i];
}

finding a number in array

I have an Array {-1,0,1,2,3,4...}
I am trying to find whether an element exist in these number or not, code is not working
NSInteger ind = [favArray indexOfObject:[NSNumber numberWithInt:3]];
in ind i am always getting 2147483647
I am filling my array like this
//Loading favArray from favs.plist
NSString* favPlistPath = [[NSBundle mainBundle] pathForResource:#"favs" ofType:#"plist"];
NSMutableDictionary* favPlistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:favPlistPath];
NSString *favString = [favPlistDict objectForKey:#"list"];
NSArray *favList = [favString componentsSeparatedByString:#","];
//int n = [[favList objectAtIndex:0] intValue];
favArray = [[NSMutableArray alloc] initWithCapacity:100];
if([favList count]>1)
{
for(int i=1; i<[favList count]; i++)
{
NSNumber *f = [favList objectAtIndex:i];
[favArray insertObject:f atIndex:(i-1)];
}
}
That's the value of NSNotFound, which means that favArray contains no object that isEqual: to [NSNumber numberWithInt:3]. Check your array.
After second edit:
Your favList array is filled with NSString objects. You should convert the string objects to NSNumber objects before inserting them in favArray:
NSNumber *f = [NSNumber numberWithInt:[[favList objectAtIndex:i] intValue]];