NSString subsstring - ios

I have a string like this
12,23,45,3,12,
What I want to do is get this each number and check with an array value. How I can get each value as a substring to check
Thanks

Break this string to array.
NSString *string = #"12,23,45,3,12,";
NSArray *array = [string componentsSeparatedByString:#","];
Then you can compare with the array.
EDIT :
As per your comment that you want to check all the string values to be present in main-other-array.
NSString *string = #"12,23,45,3,12";
NSArray *array = [string componentsSeparatedByString:#","];
//below is the main-other-array
NSArray *toCheckArray = #[#"124",#"23",#"45",#"3",#"12",#"1000"];
BOOL arrayIsContainedInToCheckArray = YES;
for (NSString *arrayObj in array) {
if (![toCheckArray containsObject:arrayObj]) {
arrayIsContainedInToCheckArray = NO;
}
}
NSLog(#"%#",arrayIsContainedInToCheckArray?#"All exist":#"All doesn't exist");

May be it helps you :
NSString *str = #"12,23,45,3,12";
NSArray *strArray = [str componentsSeparatedByString:#","];
NSArray * anotherArray = nil; // have some value
for (NSString * value in strArray)
{
int intVal = [value integerValue]; // here is your separate value
for (int i = 0; i < [anotherArray count]; i++) // You can check against another array
{
id anotherVal = [anotherArray objectAtIndex:i];
// Here you can check intVal and anotherVal from another array
}
}

Use this, It will help you..
NSArray *detailArray = [yourString componentsSeparatedByString:#","];

Related

iOS: Reorder NSString characters alphabetically [duplicate]

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

Convert NSString into NSDIctionary

I have a string ------ NSString abc = #"apple:87,banana:32,grapes:54";
i need this output like this
{
name = "apple";
value = "87";
},
{
name = "banana";
value = "32";
},
{
name = "grapes";
value = "54";
}
I have tried:
NSArray* itemList = [abc componentsSeparatedByString:#","];
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (NSString* item in itemList) {
NSArray* subItemList = [item componentsSeparatedByString:#":"];
if (subItemList.count > 0) {
[dict setObject:[subItemList objectAtIndex:1] forKey:[subItemList objectAtIndex:0]];
}
}
NSLog(#"%#", dict);
The output is --
{
apple = 87;
banana = 32;
grapes = 54;
}
but i dont want this output
The wanted output is a NSArray of NSDictionary.
So:
NSArray* itemList = [abc componentsSeparatedByString:#","];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (NSString *aString in itemList)
{
NSArray* subItem = [aString componentsSeparatedByString:#":"];
NSDictionary *dict = #{#"name":[subItem objectAtIndex:0],
#"value":[subItem objectAtIndex:1]};
[finalArray addObject:dict];
}
I didn't use the if ([subItem count] > 0), trying just to keep the logic you missed and clarify the algorithm.
I didn't test the code, but that should do it. (or maybe a little compiler error easy to correct).
In case anyone wants the equivalent in Swift:
let abc = "apple:87,banana:32,grapes:54"
let dict = abc.componentsSeparatedByString(",").map { pair -> [String: String] in
let parts = pair.componentsSeparatedByString(":")
return ["name": parts[0], "value": parts[1]]
}

fill NSArray from NSDictionary

I'm new to Objective-C, and I would like to know how I can fill my NSArray from a NSDictionary ?
My NSDictionary look like this :
user = {
items = (
{
nom = nom1;
prenom = prenom1;
},
{
nom = nom2;
prenom = prenom2;
},
{
nom = nom3;
prenom = prenom3;
}
);
};
It is based on a Json, and I want my array to be like :
"prenom1.nom1", "prenom2.nom2", "prenom3.nom3"
I've tried something like this
array = [self.users objectForKey:#"user"]
but the result is the same as in my dictionary.
You can use enumerateObjectsUsingBlock -
NSArray *itemsArray=[user objectForKey:#"items"];
NSMutableArray *outputArray=[[NSMutableArray alloc]init];
[itemsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[outputArray addObject:[NSString stringWithFormat:#"%#.%#",[obj objectForKey:#"prenom"],[obj objectForKey:#"nom"]]];
}];
outputArray will contain your names in the required format
NSDictionary *users = // your dictionary
NSArray *items = users[#"items"];
NSMutableArray *names = [NSMutableArray array];
for (NSDictionary *item in items) {
NSString *name = [NSString stringWithFormat:#"%#.%#", item[#"prenom"], item[#"nom"]];
[names addObject:name];
}
Using the dictionary you supplied this will add all the names in the format you wanted to the names array.

Printing from NSMutableArray

So i want to print the users in an NSMutableArray. But the strings keep coming out as nil.
here is what i have:
int users = 0;
- (IBAction)addNewUser:(id)sender {
NSString *string;
string = userNameTextField.text;
[usernameArray insertObject:string atIndex:users];
users++;
[self showUsers];
}
-(void)showUsers{
for (int i = 0; i < users; i++){
NSString *s = textView.text;
NSString *add;
add = [NSString stringWithFormat:#"%# ",[usernameArray objectAtIndex:i]];
NSString *display = [NSString stringWithFormat:#"%# \n %#", s, add];
textView.text = display;
}
}
i have also tried
-(void)showUsers{
for (int i = 1; i < users; i++){
NSString *s = textView.text;
NSString *add;
add = [usernameArray objectAtIndex:i];
NSString *display = [NSString stringWithFormat:#"%# \n %#", s, add];
textView.text = display;
}
}
First of all try using more comprehensive names for the objects. I'm rewriting your code.
Common Causes for the problem : Array not initialized, you are starting your for cycle with int i equal to 1, so you are missing the object at index 0 at your mutable array. Try the following code.
#interface InterfaceName : InterfaceInherits <IfDelegate> {
int usersCount;
NSMutableArray * usernameArray;
}
#implementation InterfaceName
/*There's no more confident way to initialize a variable than in the init method of the class. */
-(id)init{
usersCount = 0;
//You have to be sure that your array is not nil
usernameArray = [NSMutableArray alloc]init]];
return self;
}
- (IBAction)addNewUser:(id)sender {
NSString *username = [usernameTextField text];
[usernameArray insertObject:username atIndex:usersCount];
usersCount++;
//I'll omit the display as I'm not sure what you were doing with it.
}
-(void)showUsers{
for (int i = 0; i < usersCount; i++){
NSString *retrievedUser = [usernameArray objectAtIndex:i];
NSString *display = [NSString stringWithFormat:#"User Retrieved : %#",retrievedUser];
textView.text = display;
}
}
#end

Grouping the NSArray elements into NSMutableDictionary

I have an NSArray some thing like in the following format.
The group array is :
(
"Q-1-A1",
"Q-1-A9",
"Q-2-A1",
"Q-2-A5",
"Q-3-A1",
"Q-3-A8",
"Q-4-A1",
"Q-4-A4",
"Q-10-A2",
"Q-8-A2",
"Q-9-A2",
"Q-7-A1",
"Q-5-A2"
)
Now what i have to do is group the array elements some thing like this.
1 = ( "Q-1-A1","Q-1-A9")
2 = ("Q-2-A1","Q-2-A5",) ...
10 =("Q-10-A2")
can any one please help me how can i achieve this.
Thanks in advance.
Try
NSArray *array = #[#"Q-1-A1",
#"Q-1-A9",
#"Q-2-A1",
#"Q-2-A5",
#"Q-3-A1",
#"Q-3-A8",
#"Q-4-A1",
#"Q-4-A4",
#"Q-10-A2",
#"Q-8-A2",
#"Q-9-A2",
#"Q-7-A1",
#"Q-5-A2"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (NSString *string in array) {
NSArray *components = [string componentsSeparatedByString:#"-"];
NSString *key = components[1];
NSMutableArray *tempArray = dictionary[key];
if (!tempArray) {
tempArray = [NSMutableArray array];
}
[tempArray addObject:string];
dictionary[key] = tempArray;
}
Create an NSMutableDictionary, then iterate through your 'group array'.
For each NSString object:
get the NSArray of componentsSeparatedByString:#"-"
use the second component to create a key and retrieve the object for that key from your mutable dictionary. If its nil then set it to an empty NSMutableArray.
add the original NSString to the mutable array.
Try this
NSArray *arrData =[[NSArray alloc]initWithObjects:#"Q-1-A1",#"Q-1-A9",#"Q-2-A1",#"Q-2-A5",#"Q-3-A1",#"Q-3-A8",#"Q-4-A1",#"Q-4-A4",#"Q-10-A2",#"Q-8-A2",#"Q-9-A2",#"Q-7-A1",#"Q-5-A2", nil ];
NSMutableDictionary *dictList = [[NSMutableDictionary alloc]init];
for (int i=0; i<[arrData count];i++) {
NSArray *arrItem = [[arrData objectAtIndex:i] componentsSeparatedByString:#"-"];
NSMutableArray *arrSplitedItems = [dictList valueForKey:[arrItem objectAtIndex:1]];
if (!arrSplitedItems) {
arrSplitedItems = [NSMutableArray array];
}
[arrSplitedItems addObject:[arrData objectAtIndex:i]];
[dictList setValue:arrSplitedItems forKey:[arrItem objectAtIndex:1]];
}
NSArray *sortedKeys =[dictList allKeys];
NSArray *sortedArray = [sortedKeys sortedArrayUsingComparator:^(id str1, id str2) {
return [((NSString *)str1) compare:((NSString *)str2) options:NSNumericSearch];
}];
for (int i=0; i<[sortedArray count]; i++) {
NSLog(#"%#",[dictList objectForKey:[sortedArray objectAtIndex:i]]);
}
listOfYourMainArray/// Its YOur main Array;
temArray = (NSArray *)listOfYourMainArray; // Add Your main array to `temArray`.
NSMutableDictionary *lastDic = [[NSMutableDictionary alloc] init]; /// YOu need to creat Dictionary for arrange your values.
for (int i = 0; i< listOfYourMainArray.count; i++)
{
for (int j = 0 ; j < temArray.count; j ++)
{
if (([[temArray objectAtIndex:j] rangeOfString:[NSString stringWithFormat:#"Q-%d", i] options:NSCaseInsensitiveSearch].location != NSNotFound))
{
[lastDic setValue:[temArray objectAtIndex:j] forKey:[NSString stringWithFormat:#"%d", i]];
}
}
}
NSLog(#"%#", lastDic)

Resources