How to get first string of NSArray - ios

Pretty straightforward question:
I have an array like so:
#[#"John Doe", #"Mister Appleseed", #"Steve"];
if it has two (or more) words, I want to delete them all but the first, so the output array should looke something like this:
#[#"John", #"Mister", #"Steve"];
How do I do this?

NSArray * arr = #[#"John Doe", #"Mister Appleseed", #"Steve"];
NSMutableArray * tmp = [NSMutableArray array];
for (NSString * s in arr)
{
NSArray * cmpnts = [s componentsSeparatedByString:#" "];
[tmp addObject:cmpnts[0]];
}
arr = tmp;

Check the following code:
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
NSArray *sourceArray = #[#"John Doe", #"Mister Appleseed", #"Steve"];
for(NSString *str in sourceArray){
[finalArray addObject:[str componentsSepratedByString:#" "] objectAtIndex:0]];
}

You iterate over the array of names, split each at spaces (" "), and then grab the first object: the first name.
NSArray *nameArray = #[#"Name", #"Name Two"]; // original array
NSMutable *modifiedNameArray = [NSMutableArray new]; // new mutable array to add new names
for (NSString *fullName in nameArray) { // for loop
NSString *firstName = [[fullName componentsSeparatedByString:#" "] objectAtIndex:0]; // extract first name
[modifiedNameArray addObject:firstName]; // add first name to mutable array
}
You have to have two arrays, because you cannot mutate an array while it is being used in a loop (even if it's an NSMutableArray).

Related

Put multiple arrays in Dictionary

I am parsing a CSV file multiple times with for loop, here I need to store these arrays one by one dictionary. There are very less questions in stack about adding NSArray to NSDictionary. I am parsing CSV with below code but I strucked at storing in NSDictionary, The program is terminating and showing warning at assigning string to dictionary
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serail No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects: keysArray forKeys: string];
}
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSString *key = [NSString stringWithFormat:#"serial%d",i];
[dict setObject:keysArray forKey:key];
}
To get back data from dictionary,
NSArray *array = [dict valueForKey:#"serial24"];//to get array 24.
If I understand you correctly, you want to add the arrays to a dictionary, with the key being the string value of integer i ? What you need to do is allocate the dictionary outside your loop -
NSMutableDictionary *dict=[NSMutableDictionary new];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serial No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
dict[string]=keysArray;
}
I am not sure why you would want to do this, because this is basically an array. You could simply do -
NSMutableArray *outputArray=[NSMutableArray new];
for (NSString *keysString in csvArray) {
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
[outputArray addObject:keysArray];
}

Add in one array three or more

I have an output of nsarray like:
2014-12-16 04:55:30.345 Syndasis[17108:7559904] (
"Hello"
)
2014-12-16 04:55:30.348 Syndasis[17108:7559904] (
"Ciao"
)
2014-12-16 04:55:30.351 Syndasis[17108:7559904] (
"Hola"
)
And I don't know how to add to one NSMutableArray. If I make this:
NSMutableArray *ns = [[NSMutableArray alloc] init];
[ns addObject:array];
NSLog(#"%#",ns);
The output is:
2014-12-16 04:59:04.148 Syndasis[17180:7587364] (
(
"Hello"
)
)
2014-12-16 04:59:04.150 Syndasis[17180:7587364] (
(
"Ciao"
)
)
I get the array from:
NSMutableArray *track = [[NSMutableArray alloc] init];
NSDictionary *summary = [dct objectForKey:#"tracks"];
for (NSDictionary *tracks in summary) {
[track addObject:[tracks objectForKey:#"foreign_id"]];
}
NSArray *arrayPR = [track firstObject];
NSMutableArray *ns = [NSMutableArray arrayWithObjects:arrayPR, nil];
NSLog(#"%#",ns);
Thanks!
Track response:
2014-12-16 05:25:29.895 Syndasis[17505:7776895] (
"Hi",
"Hola"
)
2014-12-16 05:25:29.895 Syndasis[17505:7776895] (
"Ciao"
)
I want to make: Make an nsarray from the first string for ever object
2014-12-16 05:25:29.896 Syndasis[17505:7776895] (
"Hi",
"Ciao"
)
I'm not 100% clear about your question, from my understanding, I think you are looking for:
NSMutableArray *ns = [NSMutableArray arrayWithArray: firstArray];
[ns addObjectsFromArray: secondArray];
[ns addObjectsFromArray: thirdArray];
NSMutableArray *track = [[NSMutableArray alloc] init];
NSDictionary *summary = [dct objectForKey:#"tracks"];
for (NSDictionary *tracks in summary)
{
//In tracks dictionary, the object for key 'foreign_id' is a array of strings.
NSArray* lArray = [tracks objectForKey:#"foreign_id"];
//pick first object from array and add it into mutable array.
[track addObject:[lArray firstObject]];
}
NSLog(#"%#",track);
I have one more approach for you. It may be helpful.
Lets add all values in NSMutableString with one separator between each values.
Then separate each values from this string will gives you an object of array.
See below code:
NSMutableString *mString = [NSMutableString new];
for (NSDictionary *tracks in summary) {
[mString appendString:[NSString stringWithFormat:#"%#,",[tracks objectForKey:#"foreign_id"]]];
}
NSMutableArray *array = [NSMutableArray arrayWithArray:[mString componentsSeparatedByString:#","]];
mString = nil;
If albumLists is a mutable array of arrays, and you want an array of the the first objects in each subarray, you can use a KVC Collection Operator:
NSArray* firstTracks = [albumLists valueForKeyPath:#"#unionOfObjects.firstObject"];
Of course, you might have separate arrays album1 & album2 you want to do this for, so you could do this to make the array of arrays and then use the collection operator:
NSArray* firstTracks = [#[album1, album2] valueForKeyPath:#"#unionOfObjects.firstObject"];
FINALLY I GOT THE SOLUTION! I POST THE SOLUTION FOR THE PEOPLE WHO HAVE THE SAME PROBLEM.
I got remembering my past of Javascript developer.
NSMutableArray *nsarray = [NSMutableArray new];
NSArray *array = [[[dct objectForKey:#"tracks"] firstObject] objectForKey:#"foreign_id"];
[nsarray addObject:array];
int len = nsarray.count;
NSMutableArray *var = [[NSMutableArray alloc] init];
for (int i = 0; i < len; i++) {
[var addObject:nsarray[i]];
}
NSLog(#"solution %#",var);
Thanks for the help!

convert array format according to array character

I have array in this format
rows = [[NSArray alloc] initWithObjects:#"adam", #"alfred", #"ain", #"abdul", #"anastazja", #"angelica",
#"dennis" , #"deamon", #"destiny", #"dragon", #"dry", #"debug" #"drums",
#"Fredric", #"France", #"friends", #"family", #"fatish", #"funeral",
#"Mark", #"Madeline",
#"Nemesis", #"nemo", #"name",
#"Obama", #"Oprah", #"Omen", #"OMG OMG OMG", #"O-Zone", #"Ontario",
#"Zeus", #"Zebra", #"zed", nil];
But i need this in to following format
rows = #[#[#"adam", #"alfred", #"ain", #"abdul", #"anastazja", #"angelica"],
#[#"dennis" , #"deamon", #"destiny", #"dragon", #"dry", #"debug", #"drums"],
#[#"Fredric", #"France", #"friends", #"family", #"fatish", #"funeral"],
#[#"Mark", #"Madeline"],
#[#"Nemesis", #"nemo", #"name"],
#[#"Obama", #"Oprah", #"Omen", #"OMG OMG OMG", #"O-Zone", #"Ontario"],
#[#"Zeus", #"Zebra", #"zed"]];
Means that same starting character in to different dictionary
The easiest approach.
NSArray *rows = ...;
NSMutableDictionary *map = [NSMutableDictionary dictionary];
for (NSString *value in rows) {
NSString *firstLetter = [value substringToIndex:1];
if (!map[firstLetter]) {
map[firstLetter] = #[];
}
NSMutableArray *values = [map[firstLetter] mutableCopy];
[values addObject:value];
map[firstLetter] = values;
}
NSArray *finalRows = [map allValues];
Note that finalRows is not sorted.
If you want to sort your array by it's first letter, you can try this :
NSMutableArray *outputArray = [NSMutableArray new];
NSString *lastFirstLetter = nil;
for(NSString *value in rows) {
NSString *firstLetter = [[value substringToIndex:1] lowerString];
if(![lastFirstLetter isEqualToString:firstLetter]) {
lastFirstLetter = firstLetter;
[outputArray addObject:[NSMutableArray new]];
}
[[outputArray lastObject] addObject:value];
}
The idea is to iterate your input array and if the first letter of your word is different than the precedent, create a new array.

Merge arrays with its count in Objective C

I have an array like this
A = [#"aa",#"cc",#"bb",#"bb",#"cc",#"aa",#"cc"]
I need to convert it to
A = [#"x2 aa",#"x2 bb",#"x3 cc"]
Count the similar elements and create a new string, add it to new array. As shown here:
NSArray *aArray = #[#"aa", #"cc", #"bb", #"bb", #"cc", #"aa", #"cc"];
NSCountedSet *set = [NSCountedSet setWithArray:aArray];
NSMutableArray *countedArray = [NSMutableArray new];
for (NSString *str in set) {
[countedArray addObject:[NSString stringWithFormat:#"x%ld %#",[set countForObject:str], str]];
}
NSLog(#"%#",countedArray);
Output:
(
"x2 bb",
"x2 aa",
"x3 cc" )

NSString remove duplicated substrings

How can I remove duplicated substings from string? For ex. I have: aaa,bbb,ttt,bbb,rrr.
And in result I want to have aaa,bbb,ttt,rrr (deleted duplicated bbb). I hope for your help. Thanks.
You can do it like this:
NSMutableSet *seen = [NSMutableSet set];
NSMutableString *buf = [NSMutableString string];
for (NSString *s in [str componentsSeparatedByString:#","]) {
if (![seen containsObject:s]) {
[seen add:s];
[buf appendFormat:#",%#", s];
}
}
NSString *res = [buf length] ? [buf substringFromIndex:1] : #"";
Do it in three steps
1) NSArray *items = [theString componentsSeparatedByString:#","];
2) remove duplicate element from array
NSArray* array = [NSArray arrayWithObjects:#"test1", #"test2", #"test1", #"test2",#"test4", nil];
NSArray* filteredArray = [[NSArray alloc] init];
NSSet *set= [NSOrderedSet orderedSetWithArray:array];
filteredArray = [set allObjects];
3) Concate String from array
NSString *myString = [myArray componentsJoinedByString:#","];
You can use NSMutableDictionary;
In dictionary there are two elements;
1. Key
2. Value
Just set Keys as your array elements;
Special point is that 'Key' can't be duplicate;
Now just get array of Keys by using [dictionary allKeys];
Now, at this stage you have unique values in new array;

Resources