How can I generate a comma-separated string in Objective-C? - objective-c

I am trying to create comma separated string. e.g. abc,pqr,xyz
I am parsing the xml and want to generate the comma separated string of the values of nodes in xml.
I am doing the following:
if([elementName isEqualToString:#"Column"])
NSString *strTableColumn = [attributeDict objectForKey:#"value"];
I am getting different nodes value in strTableColumn while parsing and want to generate comma separated of this. Please help.

I would do to it like this. Before you start your XML processing, create a mutable array to hold each "Column" value (probably want this to be an iVar in your parser class):
NSMutableArray *columns = [[NSMutableArray alloc] init];
Then parse the XML, adding each string to the array:
if([elementName isEqualToString:#"Column"]) {
[columns addObject:[attributeDict objectForKey:#"value"]];
}
When you're done, create the comma-separated string and release the array:
NSString *strTableColumn = [columns componentsJoinedByString:#","];
[columns release];
columns = nil;

You can use the following code:
NSString *timeCreated = elementName;
NSArray *timeArray = [timeCreated componentsSeparatedByString:#","];
NSString *t = [timeArray objectAtIndex:0];
NSString *t1 = [timeArray objectAtindex:1];
Then append one by one string.

use NSMutableString
then you can use
[yourMutableString appendString:#","];//there is a comma
[yourMutableString appendString:someOtherString];
in this way your strings are separated by comma

This method will return you the nsmutablestring with comma separated values from an array
-(NSMutableString *)strMutableFromArray:(NSMutableArray *)arr withSeperater:(NSString *)saperator
{
NSMutableString *strResult = [NSMutableString string];
for (int j=0; j<[arr count]; j++)
{
NSString *strBar = [arr objectAtIndex:j];
[strResult appendString:[NSString stringWithFormat:#"%#",strBar]];
if (j != [arr count]-1)
{
[strResult appendString:[NSString stringWithFormat:#"%#",seperator]];
}
}
return strResult;
}

First thought can be that you parse the data and append commas using the NSString append methods. But that can have extra checks. So better solution is to
Parse data -> Store into array -> Add comma separators -> Finally store in string
// Parse data -> Store into array
NSMutableArray *arrayOfColumns = [[NSMutableArray alloc] init];
if([elementName isEqualToString:#"Column"]){
[arrayOfColumns addObject:[attributeDict objectForKey:#"value"]];
}
// Add comma separators -> Finally store in string
NSString *strTableColumn = [arrayOfColumns componentsJoinedByString:#","];

Related

split NSString using componentsSeparatedByString

I have a string I need to split. It would be easy using componentsSeparatedByString but my problem is that the separator is a comma but I could have commas that aren't separator.
I explain:
My string:
NSString *str = #"black,red, blue,yellow";
the comma between red and blue must not be considered as separator.
I can determine if comma is a separator or not checking if after it there is a white space.
The goal is to obtain an array with:
(
black,
"red, blue",
yellow
)
This is tricky. First replace all occurences of ', ' (comma+space) with say '|' then use components separated method. Once you are done, again replace '|' with ', ' (comma+space).
Just to complete the picture, a solution that uses a regular expression to directly identify commas not followed by white space, as you explain in your question.
As others have suggested, use this pattern to substitute with a temporary separator string and split by that.
NSString *pattern = #",(?!\\s)"; // Match a comma not followed by white space.
NSString *tempSeparator = #"SomeTempSeparatorString"; // You can also just use "|", as long as you are sure it is not in your input.
// Now replace the single commas but not the ones you want to keep
NSString *cleanedStr = [str stringByReplacingOccurrencesOfString: pattern
withString: tempSeparator
options: NSRegularExpressionSearch
range: NSMakeRange(0, str.length)];
// Now all that is needed is to split the string
NSArray *result = [cleanedStr componentsSeparatedByString: tempSeparator];
If you are not familiar with the regex pattern used, the (?!\\s) is a negative lookahead, which you can find explained quite well, for instance here.
Here is coding implementation for cronyneaus4u's solution:
NSString *str = #"black,red, blue,yellow";
str = [str stringByReplacingOccurrencesOfString:#", " withString:#"|"];
NSArray *wordArray = [str componentsSeparatedByString:#","];
NSMutableArray *finalArray = [NSMutableArray array];
for (NSString *str in wordArray)
{
str = [str stringByReplacingOccurrencesOfString:#"|" withString:#", "];
[finalArray addObject:str];
}
NSLog(#"finalArray = %#", finalArray);
NSString *str = #"black,red, blue,yellow";
NSArray *array = [str componentsSeparatedByString:#","];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (int i=0; i < [array count]; i++) {
NSString *str1 = [array objectAtIndex:i];
if ([[str1 substringToIndex:1] isEqualToString:#" "]) {
NSString *str2 = [finalArray objectAtIndex:(i-1)];
str2 = [NSString stringWithFormat:#"%#,%#",str2,str1];
[finalArray replaceObjectAtIndex:(i-1) withObject:str2];
}
else {
[finalArray addObject:str1];
}
}
NSLog(#"final array count : %d description : %#",[finalArray count],[finalArray description]);
Output:
final array count : 3 description : (
black,
"red, blue",
yellow
)

Comparing Strings From Two Files Returns Null in Objective C

Sorry in advance for this being such a beginner question. Here are the steps of what I'm trying to do:
Read two text files (unix word list files for proper names and
regular words)
Separate the text into string
Place the separated strings into an array for each list
Compare the arrays and count the number of matches
For whatever reason, this code continually returns null matches. What might I be doing? Thanks a ton for any help.
int main (int argc, const char * argv[])
{
#autoreleasepool {
// Place discrete words into arrays for respective lists
NSArray *regularwords = [[NSString stringWithContentsOfFile:#"/usr/dict/words" encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:#"\n"];
NSArray *propernames = [[NSString stringWithContentsOfFile:#"/usr/dict/propernames" encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:#"\n"];
// The compare and count loop
NSInteger *counter;
for (int i = 0; i < [propernames count]; i++) {
NSString *stringFromRegularWords = [regularwords objectAtIndex:i];
NSString *properNamesString = [propernames objectAtIndex:i];
if ([properNamesString isEqualToString:stringFromRegularWords]) {
counter++;
}
}
// Print the number of matches
NSLog(#"There was a total of %# matching words", counter);
}
return 0;
}
You're doing objectAtIndex:i, expecting the words to be in exactly same indexes in both files. What you should probably do is add entries from one of the files to an NSMutableSet and then check for membership that way.
// Place discrete words into arrays for respective lists
NSArray *regularwords = [[NSString stringWithContentsOfFile:#"/usr/dict/words" encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:#"\n"];
NSArray *propernames = [[NSString stringWithContentsOfFile:#"/usr/dict/propernames" encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:#"\n"];
// Add each of the words to a set so that we can quickly look them up
NSMutableSet* wordsLookup = [NSMutableSet set];
for (NSString* word in regularwords) {
[wordsLookup addObject:word];
}
NSInteger *counter;
for (NSString *properName in propernames) {
// This efficiently checks if the properName occurs in wordsLookup
if ([wordsLookup containsObject:properName]) {
counter++;
}
}
Note that my example also uses "fast enumeration," i.e. the for ... in syntax. While not necessary to solve your problem, it does make the code shorter and arguably faster.

How to replace the Space with UnderScore( _ ) in the array in objective C

How to replace the Space with UnderScore( _ ) in the array in objective C.
The following is the code i am using to read the array data from the file,
NSString *g = [[NSString alloc]initWithCString:data];
NSMutableString *tempGetAll = [[NSMutableString alloc]init];
if(k>0){
NSArray *lines = [g componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#""]];
for (NSString* line in lines)
{
//[arrGetAll addObject: line];
NSLog(#"%#",line) ;
//NSLog(#"---------");
}
}
k++;
The following is the output i am getting,
hi how r u 20.000
But i need the output in the following way,
hi_how_r_u:20.000
so how to replace the space with the Underscore.
There is a method stringByReplacingOccurrencesOfString:withString:
NSString* string1 = #"123 123 123";
NSString* string2 = [string1 stringByReplacingOccurrencesOfString:#" " withString:#"_"];
NSLog(#"%#", string2);
Result is
123_123_123
In order to create a string from an array by joining its elements you must use NSArray's:
- (NSString *)componentsJoinedByString:(NSString *)separator
In your case it is:
NSString *getAll = [lines componentsJoinedByString:#"_"];
Essentially "componentsSeparatedByCharactersInSet" splits a string to an array, "componentsJoinedByString" joins array components in one string.

Accept string values in NSArray from the user

hi i want to accept string values into the object of NSArray at run time from the user heres what i tried
-(void)fun
{
NSArray *arr = [[NSArray alloc]init];
for(int i =0;i<3;i++)
{
scanf("%s",&arr[i]);
}
printf("Print values\n");
for(int j =0; j<3;j++)
{
printf("\n%s",arr[j]);
}
}
i am getting an error can you please help me out regarding this and is their any alternative to scanf in objective c.
Thank you
scanf() with a %s format will read the string into a C array, not an NSArray object. You need to read the string into a C array, then make an NSString object to add to your NSArray. You also need to have a mutable array to make your code work. Example:
NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:3];
for (int i = 0; i < 3; i++)
{
char buf[100];
scanf("%s", buf);
NSString *str = [NSString stringWithCString:buf encoding:NSASCIIStringEncoding];
[arr addObject:str];
}
You can use NSLog() to print your strings later on.
use NSMutableArray instead;
than you can use also
[arr addObject:tempVar];

Generating an NSDictionary from an SQL statement

I am trying to generate an NSDictonary that can be used to populate a listview with data I retrieved from an SQL statement. when I go to create an array and add them it adds the arrays for ALL my keys and not just for the current key. I've tried a removeAllObjects on the array but for some reason that destroys ALL my data that I already put in the dictionary.
//open the database
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "select alphaID, word from words order by word";
sqlite3_stmt *selectStatement;
//prepare the select statement
int returnValue = sqlite3_prepare_v2(database, sql, -1, &selectStatement, NULL);
if(returnValue == SQLITE_OK)
{
NSMutableArray *NameArray = [[NSMutableArray alloc] init];
NSString *alphaTemp = [[NSString alloc] init];
//loop all the rows returned by the query.
while(sqlite3_step(selectStatement) == SQLITE_ROW)
{
NSString *currentAlpha = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, 1)];
NSString *definitionName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, 2)];
if (alphaTemp == nil){
alphaTemp = currentAlpha;
}
if ([alphaTemp isEqualToString:(NSString *)currentAlpha]) {
[NameArray addObject:definitionName];
}
else if (alphaTemp != (NSString *)currentAlpha) {
[self.words setObject:NameArray forKey:currentAlpha];
[NameArray removeAllObjects];
[NameArray addObject:definitionName];
}
}
}
The Statement above adds all the "keys" but then removes all the array elements for all keys. if I take out the removeAllKeys it adds ALL the array elements for ALL keys. I don't want this I want it to add the array elements FOR the specific key then move on to the next key.
in the end I want a NSDictonary with
A (array)
Alpha (string)
Apple (string)
B (array)
Beta (string)
Ball (string)
C (array)
Code (string)
...
Though I don't think it affects your problem, from the way I read your code, you should change
NSString *alphaTemp = [[NSString alloc] init];
to
NSString *alphaTemp = nil;
since alphaTemp is just used to point to an NSString that is generated initially as currentAlpha. You also should call [NameArray release] at some point below the code you've given, since you alloc'd it.
The real issue is that you are repeatedly adding pointers to the same NSMutableArray to your NSDictionary (self.words). I can see two ways to fix this:
Change
[self.words setObject:NameArray forKey:currentAlpha];
to
[self.words setObject:[NSArray arrayWithArray:NameArray] forKey:currentAlpha];
so that you are adding a newly-created (non-mutable) NSArray to your NSDictionary.
-- or --
Insert
[NameArray release];
NameArray = [[NSMutableArray alloc] init];
after
[self.words setObject:NameArray forKey:currentAlpha];
so that once you've inserted the NSMutableArray into the NSDictionary, you create a new NSMutableArray for the next pass.