I have a for-in loop running unknown num of times, when its finished running I want to have all names appending like so: name1, name2,name3 and so on.
How do I append the strings within the loop ?
I was thinking of something like this :
if (donePressed)
{
NSString *allFriends;
selectedFriends = friendPicker.selection;
for (NSDictionary * friend in selectedFriends)
{
NSString * friendName = [friend objectForKey:#"name"];
// some built-in method that appends friendName to allFriends with a ", " between them
}
NSLog(#"%#",selectedFriends);
}
NSString *allFriends = [[friendPicker.selection valueForKey:#"name"] componentsJoinedByString:#", "];
I would do this:
NSMutableString *nameString = [[NSMutableString alloc]init];
for loop (...) {
NSString *currentName = [friend objectForKey:#"name"];
[nameString appendString:[NSString stringWithFormat:#"%#, ",currentName]];
}
NSLog(#"%#",nameString);
The answer above mine looks better, that function probably doesn't leave a trailing , at the end of the list. Mine would have to use NSMakeRange() to trim the trailing comma.
Related
I have this code who chunks a string existing inside a NSString into a NSMutableArray:
NSString *string = #"one/two/tree";
NSMutableArray *parts = [[string componentsSeparatedByString:#"/"] mutableCopy];
NSLog(#"%#-%#-%#",parts[0],parts[1],parts[2]);
This command works perfectly but if the NSString is not obeying this pattern (not have the symbol '/' within the string), the app will crash.
How can I check if it is possible to break the NSString, preventing the app does not crash?
Just check parts.count if you don't have / in your string (or only one), you won't get three elements.
NSString *string = #"one/two/tree";
NSMutableArray *parts = [[string componentsSeparatedByString:#"/"] mutableCopy];
if(parts.count >= 3) {
NSLog(#"%#-%#-%#",parts[0],parts[1],parts[2]);
}
else {
NSLog(#"Not found");
}
From the docs:
If list has no separators—for example, "Karin"—the array contains the string itself, in this case { #"Karin" }.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:
You might be better off using the "opposite" function to put it back together...
NSString *string = #"one/two/three";
NSArray *parts = [string componentsSeparatedByString:#"/"];
NSString *newString = [parts componentsJoinedByString:#"-"];
// newString = #"one-two-three"
This will take the original string. Split it apart and then put it back together no matter how many parts there are.
I'm getting a response from webservice as a string like below one -
brand=company%%samsung##modelnumber=webmodel%%GT1910##Sim=Single%%SingleSim##3g=yes%%Yes##wifi=yes%%yes(2.1 mbps upto)
I'm confusing that to format my response like below one -
brand=samsung
modelnumber=GT1910
Sim=SingleSim
3g=Yes
wifi=(2.1 mbps upto)
I've tried to remove the special characters (## and %%)
specialString = [specialString stringByReplacingOccurrencesOfString:#"##" withString:#"\n"];
specialString = [specialString stringByReplacingOccurrencesOfString:#"%%" withString:#"\n"];
specialString= [specialString stringByReplacingOccurrencesOfString:#" " withString:#""];
My output was -
brand=company
samsung
modelnumber=webmodel
GT1910
Sim=Single
SingleSim
3g=yes
Yes
wifi=yes
(2.1 mbps upto)
How to remove unwanted words.
You can't use simple find and replace because there are parts of the original string you don't want.
Untested, but this will probably work:
NSArray *parts = [specialstring componentsSeparatedByString:#"##"];
NSMutableArray *result = [[NSMutableArray alloc] init];
for(NSString *piece in parts) {
NSArray *pairs = [piece componentsSeparatedByString:#"="];
if([pairs count] > 1) {
NSString *key = [pairs objectAtIndex:0];
NSString *values = [pairs objectAtIndex:1];
NSArray *avalues = [values componentsSeparatedByString:#"%%"];
[result addObject:[NSString stringWithFormat:#"%#=%#", key, [avalues lastObject]]];
}
}
NSLog(#"%#", [result componentsJoinedByString:#"\n"]);
// [result release]; // Uncomment if ARC is turned off
First splits by ## and iterates over array. Then splits by = to get key on left side (index 0). Takes right side (index 1) and splits by %% and uses last value.
Trim like below it will work
NSString *strRes = #"brand=company%%samsung##modelnumber=webmodel%%GT1910##Sim=Single%%SingleSim##3g=yes%%Yes##wifi=yes%%yes(2.1 mbps upto)";
strRes = [strRes stringByReplacingOccurrencesOfString:#"=" withString:#"--"];
strRes = [strRes stringByReplacingOccurrencesOfString:#"##" withString:#"\n"];
NSRange rangeForTrim;
while ((rangeForTrim = [strRes rangeOfString:#"--[^%%]+%%" options:NSRegularExpressionSearch]).location != NSNotFound)
strRes = [strRes stringByReplacingCharactersInRange:rangeForTrim withString:#"="];
NSLog(#"%#",strRes);
Well, I can't write the code right away but here's what you gotta do:
Replace all %% with (space)
Replace all ## with \n
Remove all words between = and (space)
I'm new to ios, trying to do something like this
self.dataArray = [dictionary valueForKey:#"LIST"];
{
"List": [
{
"FULLNAME": "FirstName, LastName",
"ID": "281"
}
]
}
I want to swap the value which is in 'FULLNAME', that is I want it to be LastName, FirstName
I tried various methods but it would not work. Can someone tell me how to accomplish this?
Thank you
Assuming you know how to do the dictionary manipulation, here's one way to swap the elements in the string:
NSString* name = #"Firstname, Lastname";
// Remove the space after comma (not necessary if you know the name will always
// have a space after comma, then just split on ', '.
NSString* normalizedName = [name stringByReplacingOccurrencesOfString:#", " withString:#","];
// Split the string on ','.
NSArray* nameParts = [normalizedName componentsSeparatedByString:#","];
// Reverse the array
NSArray* reverseNameParts = [[nameParts reverseObjectEnumerator] allObjects];
// Join the array with ', '
NSString* revname = [reverseNameParts componentsJoinedByString:#", "];
NSLog(#"Reversed name parts: %#", revname);
I believe it should be objectForKey instead of valueForKey, if your dictionary contains arrays.
self.dataArray = [dictionary objectForKey:#"LIST"];
for(NSString *fullname in self.dataArray){
if([fullname isEqualToString:#"FULLNAME"]){
NSArray *name = [fullname componentsSeparatedByString:#","];
NSMutableString* reverseName = [NSMutableString string];
for (int i=[name count]-1; i>=0;i--){
[reverseName appendFormat:#", ", [name objectAtIndex:i]];
//reverse name should be what you are looking for..or something close
}
}
}
hope this helps
I have an array where i am trying to remove the access spaces, brackets and " from the nsarray in order to use componentsSeparatedByString:#";"
NSArray *paths = [dic valueForKey:#"PATH"];
for(NSString *s in paths)
{
NSLog(#"String: %#", s);
}
String: (
"29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043"
)
this is the output give as show there are spaces, brackets and " how could i remove them
?
As this line is juz a string inside that array "29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043" this line is a string inside the path array and i try using componentsSeparatedByString:#";" it could not be spilt all there are spaces brackets and " inside.
Try stringByTrimmingCharactersInSet:
NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:#"() \n\""];
s = [s stringByTrimmingCharactersInSet:charsToTrim];
try to use:
s = [s stringByReplacingOccurrencesOfString:#";"
withString:#""];
it separates the numbers for you and you can work with them as i.e. NSInteger values.
NSString *_inputString = #"29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043";
NSString *_setCommonSeparator = [_inputString stringByReplacingOccurrencesOfString:#";" withString:#","];
NSArray *_separetedNumbers = [_setCommonSeparator componentsSeparatedByString:#","];
for (NSString *_currentNumber in _separetedNumbers) {
NSInteger _integer = [_currentNumber integerValue];
NSLog(#"number : %d", _integer);
}
I have a search string, where people can use quotes to group phrases together, and mix this with individual keywords. For example, a string like this:
"Something amazing" rooster
I'd like to separate that into an NSArray, so that it would have Something amazing (without quotes) as one element, and rooster as the other.
Neither componentsSeparatedByString nor componentsSeparatedByCharactersInSet seem to fit the bill. Is there an easy way to do this, or should I just code it up myself?
You probably will have to code some of this up yourself, but the NSScanner should be a good basis on which to build. If you use the scanUpToCharactersInSet method to look for everything up to your next whitespace or quote character to can pick off words. Once you encounter a quite character, you could continue to scan using just the quote in the character set to end at, so that spaces within the quotes don't result in the end of a token.
I made a simple way to do this using NSScanner:
+ (NSArray *)arrayFromTagString:(NSString *)string {
NSScanner *scanner = [NSScanner scannerWithString:string];
NSString *substring;
NSMutableArray *array = [[NSMutableArray alloc] init];
while (scanner.scanLocation < string.length) {
// test if the first character is a quote
unichar character = [string characterAtIndex:scanner.scanLocation];
if (character == '"') {
// skip the first quote and scan everything up to the next quote into a substring
[scanner setScanLocation:(scanner.scanLocation + 1)];
[scanner scanUpToString:#"\"" intoString:&substring];
[scanner setScanLocation:(scanner.scanLocation + 1)]; // skip the second quote too
}
else {
// scan everything up to the next space into the substring
[scanner scanUpToString:#" " intoString:&substring];
}
// add the substring to the array
[array addObject:substring];
//if not at the end, skip the space character before continuing the loop
if (scanner.scanLocation < string.length) [scanner setScanLocation:(scanner.scanLocation + 1)];
}
return array.copy;
}
This method will convert the array back to a tag string, re-quoting the multi-word tags:
+ (NSString *)tagStringFromArray:(NSArray *)array {
NSMutableString *string = [[NSMutableString alloc] init];
NSRange range;
for (NSString *substring in array) {
if (string.length > 0) {
[string appendString:#" "];
}
range = [substring rangeOfString:#" "];
if (range.location != NSNotFound) {
[string appendFormat:#"\"%#\"", substring];
}
else [string appendString:substring];
}
return string.description;
}
I ended up going with a regular expression as I was already using RegexKitLite, and creating this NSString+SearchExtensions category.
.h:
// NSString+SearchExtensions.h
#import <Foundation/Foundation.h>
#interface NSString (SearchExtensions)
-(NSArray *)searchParts;
#end
.m:
// NSString+SearchExtensions.m
#import "NSString+SearchExtensions.h"
#import "RegexKitLite.h"
#implementation NSString (SearchExtensions)
-(NSArray *)searchParts {
__block NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:5];
[self enumerateStringsMatchedByRegex:#"\\w+|\"[\\w\\s]*\"" usingBlock: ^(NSInteger captureCount,
NSString * const capturedStrings[captureCount],
const NSRange capturedRanges[captureCount],
volatile BOOL * const stop) {
NSString *result = [capturedStrings[0] stringByReplacingOccurrencesOfRegex:#"\"" withString:#""];
NSLog(#"Match: '%#'", result);
[items addObject:result];
}];
return [items autorelease];
}
#end
This returns an NSArray of strings with the search strings, removing the double quotes that surround the phrases.
If you'll allow a slightly different approach, you could try Dave DeLong's CHCSVParser. It is intended to parse CSV strings, but if you set the space character as the delimiter, I am pretty sure you will get the intended behavior.
Alternatively, you can peek into the code and see how it handles quoted fields - it is published under the MIT license.
I would run -componentsSeparatedByString:#"\"" first, then create a BOOL isPartOfQuote, initialized to YES if the first character of the string was a ", but otherwise set to NO.
Then create a mutable array to return:
NSMutableArray* masterArray = [[NSMutableArray alloc] init];
Then, create a loop over the array returned from the separation:
for(NSString* substring in firstSplitArray) {
NSArray* secondSplit;
if (isPartOfQuote == NO) {
secondSplit = [substring componentsSeparatedByString:#" "];
}
else {
secondSplit = [NSArray arrayWithObject: substring];
}
[masterArray addObjectsFromArray: secondSplit];
isPartOfQuote = !isPartOfQuote;
}
Then return masterArray from the function.