Get substring from string variable and save to NSMutableArray [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am new to iOS development and facing some problem. I have a string like this M||100|??|L||150|??|S||50. I want to break the string into chunks and save to array, e.g M 100 is on 1st index, L 150 on second index, S 50 on third index.

NSString *str = #"M||100|??|L||150|??|S||50";
NSString *stringWithoutBars = [str stringByReplacingOccurrencesOfString:#"||" withString:#" "];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[stringWithoutBars componentsSeparatedByString:#"|??|"]];

You can get Array from your string using this code
NSString *str = #"M||100|??|L||150|??|S||50";
str = [str stringByReplacingOccurrencesOfString:#"||" withString:#" "];
NSArray *array = [str componentsSeparatedByString:#"|??|"];
this will return your expected result.

let str = "M||100|??|L||150|??|S||50"
let array = str.componentsSeparatedByString("|??|")
print(array)
result :
["M||100", "L||150", "S||50"]

///First replace "||" with " "
NSString *your_str = #"M||100|??|L||150|??|S||50";
your_str = [your_str stringByReplacingOccurrencesOfString:#"||" withString:#" "];
///Get array of string
NSArray *arr = [your_str componentsSeparatedByString:#"|??|"];
NSMutableArray *data_arr = [[NSMutableArray alloc] init];
for(NSString *str in arr)
{
///string to data conversion
NSData *data = [your_str dataUsingEncoding:NSUTF8StringEncoding];
//////// add data to array
[data_arr addObject: data];
}
NSLog(#"data_arr =%#",data_arr);

NSString *str = #"M||100|??|L||150|??|S||50";
NSArray *arrt = [str componentsSeparatedByString:#"|??|"];
NSMutableArray *arr = [[NSMutableArray alloc]init];
for (int i = 0; i <= arrt.count - 1; i++) {
[arr addObject:[[arrt objectAtIndex:i] componentsSeparatedByString:#"||"]];
}

Related

Want to reverse some specific word form given string using NSString in ios [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am new to objective c as well as to iOS.
I have one string like this
NSString *string1 = #"My name is john";
I want to reverse only 'john' to 'nhoj'.
Please Help me!!!.
Thank You
Try This, It will produce your desire output.
NSString *strName = #"My name is john" ;
NSArray *arrStringPart = [strName componentsSeparatedByString:#" "];
NSString *strToReverse = [arrStringPart objectAtIndex:arrStringPart.count - 1];
int len = (int)[strToReverse length];
NSMutableString *mutStrReverce = [[NSMutableString alloc] initWithCapacity:strName.length];
for(int i=0;i<arrStringPart.count-1;i++)
{
[mutStrReverce appendString:[NSString stringWithFormat:#"%# ",[arrStringPart objectAtIndex:i]]];
}
for(int i=len-1;i>=0;i--)
{
[mutStrReverce appendString:[NSString stringWithFormat:#"%c",[strToReverse characterAtIndex:i]]];
}
NSLog(#"%#",mutStrReverce);
Here you go.
May following snippet help you.
NSString *string1 = #"My name is john";
NSArray *arr = [string1 componentsSeparatedByString:#" "];
NSString *temp_sre = [arr objectAtIndex:arr.count - 1];
int len = [temp_sre length];
NSMutableString *reverseName = [[NSMutableString alloc] initWithCapacity:len];
for(int i=len-1;i>=0;i--)
{
[reverseName appendString:[NSString stringWithFormat:#"%c",[temp_sre characterAtIndex:i]]];
}
NSLog(#"reverseName = %#",reverseName);
NSMutableArray *final_array = [[NSMutableArray alloc] init];
final_array = arr.mutableCopy;
[final_array removeLastObject];
[final_array insertObject:reverseName atIndex:final_array.count];
NSString *final_string = [final_array componentsJoinedByString:#" "];
NSLog(#"FInal String = %#",final_string);

How to trim string till first alphabet in a alphanumeric string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a alpha numeric string as 24 minutes i want to trim it like 24mplease tell me how can i do this ?
try use code in regex:
NSString *string = #"24 minutes";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"([0-9]+)[^a-zA-Z]*([a-zA-Z]{1}).*" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#"$1$2"];
NSLog(#"%#", modifiedString);
output:
24m
You can use the componentsSeparatedByString: and substringToIndex: methods of NSString Class, to achieve the result.
NSString *str = #"24 minutes";
NSArray *components = [str componentsSeparatedByString:#" "];
// Validation to prevent array out of index crash (If input is 24)
if ([components count] >= 2)
{
NSString *secondStr = components[1];
// Validation to prevent crash (If input is 24 )
if (secondStr.length)
{
NSString *shortName = [secondStr substringToIndex:1];
str = [NSString stringWithFormat:#"%#%#",components[0],shortName];
}
}
NSLog(#"%#",str);
This example works with the above string, however you need to take care of different type of inputs. It can fail if there is multiple spaces between those values.
NSString *aString = #"24 minutes"; // can be "1 minute" also.
First divide the string into two components:
Divide it with white space, since your string can contain one or more number also like "1 minute", "24 mintutes".
NSArray *array = [aString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
array = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF != ''"]];
NSLog(#"%#",[array objectAtIndex:0]);
Then fetch the first letter of the second component of the string using substringToIndex and finally combine both the strings.
NSString * firstLetter = [[array objectAtIndex:1] substringToIndex:1];
NSString *finalString = [[array objectAtIndex:0] stringByAppendingString:firstLetter];
NSLog(#"%#",finalString);

how to convert NSString to NSArray [duplicate]

This question already has answers here:
Comma-separated string to NSArray in Objective-C
(2 answers)
Closed 8 years ago.
I have a string like
NSString* str = #"[90, 5, 6]";
I need to convert it to an array like
NSArray * numbers = [90, 5 , 6];
I did a quite long way like this:
+ (NSArray*) stringToArray:(NSString*)str
{
NSString *sep = #"[,";
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
NSArray *temp=[str componentsSeparatedByCharactersInSet:set];
NSMutableArray* numbers = [[NSMutableArray alloc] init];
for (NSString* s in temp) {
NSNumber *n = [NSNumber numberWithInteger:[s integerValue]];
[numbers addObject:n];
}
return numbers;
}
Is there any neat and quick way to do such conversion?
Thanks
First remove the unwanted characters from the string, like white spaces and braces:
NSString* str = #"[90, 5, 6]";
NSCharacterSet* characterSet = [[NSCharacterSet
characterSetWithCharactersInString:#"0123456789,"] invertedSet];
NSString* newString = [[str componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""];
You will have a string like this: 90,5,6. Then simply split using the comma and convert to NSNumber:
NSArray* arrayOfStrings = [newString componentsSeparatedByString:#","];
NSMutableArray* arrayOfNumbers = [NSMutableArray arrayWithCapacity:arrayOfStrings.count];
for (NSString* string in arrayOfStrings) {
[arrayOfNumbers addObject:[NSDecimalNumber decimalNumberWithString:string]];
}
Using the NSString category from this response it can be simplified to:
NSArray* arrayOfStrings = [newString componentsSeparatedByString:#","];
NSArray* arrayOfNumbers = [arrayOfStrings valueForKey: #"decimalNumberValue"];
NSString* str = #"[90, 5, 6]";
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:#"[] "];
NSArray *array = [[[str componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""]
componentsSeparatedByString:#","];
Try like this
NSArray *arr = [string componentsSeparatedByString:#","];
NSString *newSTR = [str stringByReplacingOccurrencesOfString:#"[" withString:#""];
newSTR = [newSTR stringByReplacingOccurrencesOfString:#"]" withString:#""];
NSArray *items = [newSTR componentsSeparatedByString:#","];
You can achieve that using regular expression 
([0-9]+)
NSError* error = nil;
NSString* str = #"[90, 5, 6]";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"([0-9]+)" options:0 error:&error];
NSArray* matches = [regex matchesInString:str options:0 range:NSMakeRange(0, [str length])];
Then you have a NSArray of string, you just need to iterate it and convert the strings to number and insert them into an array.

how to get string removing parameters [duplicate]

This question already has answers here:
Remove characters from NSString?
(6 answers)
Closed 8 years ago.
I am getting string from json dictionory but result string is in brackets, i have to get string without backets
code is
jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *dictResult = [jsonDictionary objectForKey:#"result"];
NSDictionary *dictPronunciations = [dictResult valueForKey:#"pronunciations"];
NSDictionary *dictAudio = [dictPronunciations valueForKey:#"audio"];
NSString *strMp3Path = [dictAudio valueForKey:#"url"];
NSLog(#"str mp3 path %#",strMp3Path);
and result is
(
(
"/v2/dictionaries/assets/ldoce/gb_pron/abate0205.mp3"
)
)
I want to get /v2/dictionaries/assets/ldoce/gb_pron/abate0205.mp3 as a string without brackets. Please help...
The object you are logging is not a NSString instance. it is a string inside an array in an array.
try:
NSLog(#"str mp3 path %#",strMp3Path[0][0]);
if this prints as desired, the object dictAudio holds with the key url is an array, with an array. you should fix that where ever you stick it into the dictionary.
Try with following code:
NSMutableArray *myArray = [dictAudio valueForKey:#"url"];
NSString *myStr = [[myArray objectAtIndex:0] objectAtIndex:0];
NSLog(#"%#", myStr);
Use this code. If your values are multiple from json then the value can be added one by one without braces :
NSMutableArray *dictPronunciations = [dictResult valueForKey:#"pronunciations"];
NSMutableArray *arrayPronunciations = [[NSMutableArray alloc] init];
for (int i = 0; i< [dictPronunciations count]; i++)
{
NSString *string = [dictPronunciations objectAtIndex:i];
NSLog(#"String = %#",string);
[arrayPronunciations addObject:string];
}
NSLog(#"Array Pronounciations = %#",arrayPronunciations);

Can't store all data from NSArray into NSMutableDictionary? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
What's the problem with this code?? I am trying to put the data from an NSArray to a NSMutableDictionary but I do not want to first split the initial nsarray into two and then send the data to the nsdcitionary.
The problem is that when I NSLog de mutabledictionary it returns me just the 1 item which happens to be the last data from the NSArray.
NSString *str = #"13:00,2.00,13:05,2.03,13:10,2.07,13:15,2.01,13:20,2.08,13:25,2.10,13:30,2.15";
NSArray *arrayFinal = [str componentsSeparatedByString:#","];
NSMutableDictionary *dict = [NSMutableDictionary new];
for (int i = 0; i < [arrayFinal count ]; i = i + 2) {
[dict setObject:[arrayFinal objectAtIndex:i] forKey:#"hora"];
[dict setObject:[arrayFinal objectAtIndex:i+1] forKey:#"preco"];
}
The result is:
2013-09-04 20:27:33.732 separa[1438:c07] {
hora = "13:30";
preco = "2.15";
}
Any help will be appreciated.
for (int i = 0; i < [arrayFinal count ]; i = i + 2) {
[dict setObject:[arrayFinal objectAtIndex:i+1] forKey:[arrayFinal objectAtIndex:i]];
}
You need each key to point to an array of values. Something like this:
NSString *str = #"13:00,2.00,13:05,2.03,13:10,2.07,13:15,2.01,13:20,2.08,13:25,2.10,13:30,2.15";
NSArray *arrayFinal = [str componentsSeparatedByString:#","];
NSMutableArray *horas = [NSMutableArray new];
NSMutableArray *precos = [NSMutableArray new];
for (int i = 0; i < [arrayFinal count]; i += 2) {
[horas addObject:arrayFinal[i]];
[precos addObject:arrayFinal[i + 1]];
}
NSMutableDictionary *dict = [NSMutableDictionary new];
dict[#"hora"] = horas;
dict[#"preco"] = precos;
You're going to need to separate the two (hours and prices) into their own NSMutableArrays, then store each array as one of the keys, something like this:
NSMutableArray *hora = [NSMutableArray alloc] init];
NSMutableArray *preco = [NSMutableArray alloc] init];
NSString *str = #"13:00,2.00,13:05,2.03,13:10,2.07,13:15,2.01,13:20,2.08,13:25,2.10,13:30,2.15";
NSArray *arrayFinal = [str componentsSeparatedByString:#","];
NSMutableDictionary *dict = [NSMutableDictionary alloc] init];
for (int i = 0; i < [arrayFinal count ]; i = i + 2)
{
[hora addObject:[arrayFinal objectAtIndex:i];
[preco addObject:[arrayFinal objectAtIndex:i+1];
}
[dict setObject:hora forKey:#"hora"];
[dict setObject:preco forKey:#"preco"];
Probably not exactly the way I'd do it, but I think it is the concept you're looking for.

Resources