Unknown quotation marks added to string object in NSMutableArray after for loop - ios

I have an array of NSString objects, the objects have some unneccessary chars (one object looks like this in the console: "\"stringContent\"") that I'm removing with the below code. It works correctly, however when I log arr1 50-60% of the strings got a quotation marks like this "stringContent", the others don't have it. Actually my problem is that I don't have an why it happens, because when I log the strings in the for loop they don't have the quotation marks. Do anybody has an idea what can causes this?
NSMutableArray * arr1 = [[NSMutableArray alloc ]init];
for (NSString *str in self.stringArray) {
NSString *newString = [str substringToIndex:[brand length]-1];
NSString *nwstr = [newString substringFromIndex:1];
[arr1 addObject:nwstr];
NSLog(#"string %#", nwstr);
}
NSLog(#"array %#", arr1);
Other thing that might be helpful, when I call this every object appears in the console, it's like the quotation marks are hidden for the containsString method, because a lot of them don't meet the requirement of the if statement.
for (NSString *str in arr1) {
if (![str containsString:#"\""]) {
NSLog(#"XXX %#", str);
}
}

When you NSLog an NSArray or NSDictionary, the elements are displayed in a log format which MAY (or may not) include gratuitous quotation marks, escaped characters, etc. Specifically, quotation marks are used around strings, EXCEPT when the strings contain no non-alphabetic characters or blanks.
More detail: What actually happens is that NSLog internally invokes [NSString stringWithFormat:] or one of its kin to format the text to be logged. stringWithFormat:, in turn, invokes the description method of each object in the parameter list that corresponds to a %# format directive. It is the description method of NSArray and NSDictionary which adds the extra characters.

Related

Remove brackets from NSMutableString

I have a NSMutableString like this:
(
993,
12836,
10630
)
how can i remove brackets?
EDIT
the string is the result of this instruction:
NSMutableString * result = [labelpost description];
You shouldn't rely on the description method as the format of the output it gives you is not guaranteed.
Instead, use a specific method on the object, like for an NSArray instance, use componentsJoinedByString: to create your desired string output.
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"()"]]
If it's NSString you can remove it by call:
string = [string stringByReplacingOccurancesOfString:#"(" withString:#""];
string = [string stringByReplacingOccurancesOfString:#")" withString:#""];
It looks to me like labelpost is an array. The method description generates a string that describes the contents of the object. In the case of an array, you get an open paren, then a comma-separated list of objects, then a closing bracket.
As the other poster, Greg, said, you can use stringByReplacingOccurancesOfString to convert your parens to empty strings, but then you will be left with
993,
12836,
10630
(With a blank line at the top containing a single space, newlines after every line, commas, and a space after the last object, and a final blank line.)
If that's what you want, fine. What is your final goal?
Try logging the class of labelpost and its contents:
NSLog(#"label post class = %#", [labelpost class]);
if ( [labelpost isKindOfClass:[NSArray class]] )
{
NSArray *array = (NSArray *)labelpost; //Cast labelpost to an array
for (id anObject in array)
NSlog(#"Object class = %#, object = %#", [anObject class] [anObject description]);
}

NSString characterSetWithCharactersInString returns empty strings

I'm trying to break a NSString into the comma separated components. Somehow my NSString containing 25000 components always returns 25.500 values, 500 of which are empty NSStrings. Here's what my code looks like:
NSString* fileContents = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:nil];
/* do stuff */
NSMutableArray* components =
[NSMutableArray arrayWithArray:
[fileContents componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#",\n\r "]]];
Consider this example:
[#"\n,\n"componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#",\n\r "]];
The result shows how componentsSeparatedByCharactersInSet: behaves. Four components, all empty strings. Do you see why?
I'm not quite sure what you were expecting it to do, but that is what it does do. It just splits at any of the characters you list. If two of them are next to each other, you get an empty string. Plus a string for before the first one and a string for after the last one.
So the reason you are getting 25500 components is that, given the command you gave, that is how many components there are.

How do I break in the NSArray with NSString substrings enclosed in quotes

I have a NSSring:
NSString *example = #"'example01','example02','example03','example04'";
How can I make from this line NSArray?
NSString *example = [example stringByReplacingOccurrencesOfString:#"'" withString:#""];
NSArray * exampleArr = [example componentsSeparatedByString:#","];
NSArray *commaSeparatedComponents = [example componentsSeparatedByString:#","];
NSCharacterSet *quotesSet = [NSCharacterSet characterSetWithCharactersInString:#"'"];
for (NSString *component in commaSeparatedComponents) {
NSString *correctlyTrimmedComponent = [component stringByTrimmingCharactersInSet:quotesSet]; // only remove 's at the edges
// ... do something with each component; maybe add to a mutable array ...
}
This has the advantage over the other answer to not remove quotes that exist inside the values, but it doesn't do anything to actually solve quotes escaping that might have been necessary inside the data, and so on. It still misbehaves with some strings, but it misbehaves for fewer cases because it is less flippant about which quotes it removes.
If this is anything above and beyond a string in that exact format, you will probably need a parser for this sort of string that can handle the semantics of how the quotes are escaped, gracefully handles garbage, etc.

Accented character incorrectly encoding in NSString Array

?I'm building a NSMutableArray of NSStrings from a list and some of the letters are accented (Turkish). I have been able to encode into a NSString and NSLog the results. But when I add that NSString to my NSMutableArray the encoding is incorrect.
This works:
NSString* temp = [[NSString alloc] init];
char *str = "üç";
temp = [NSString stringWithUTF8String:"üç"];
NSLog(#"str: %#",temp);
Logged output:
2012-06-09 09:09:18.398 Fluent[1821:f803] str: üç
When I try to add it to my NSMutableArray like this:
ones = [NSArray arrayWithObjects:#"",#"bir",#"iki",temp,#"dört",#"beş",#"altı",#"yedi",#"sekiz",#"dokuz",nil];
NSLog(#"ones: %#",ones);
It loses the encoding:
2012-06-09 09:09:18.399 Fluent[1821:f803] ones: (
"",
bir,
iki,
"\U00fc\U00e7",
"d\U00f6rt",
"be\U015f",
"alt\U0131",
yedi,
sekiz,
dokuz)
Any ideas on how to do this? The posts I have read around this area seem to be focused on transfer over HTTP.
I'd like a simpler approach such as to encode a C-string if this is necessary and then unstring by spaces into the array.
Your strings aren't incorrectly encoded. What you see is an artifact of writing a complete array to the log. In this case, the array is first converted to the property list format and then written to the log.
If you create a loop and write each element separately to the log, you'll see that everything is ok:
NSUInteger count = [ones count];
for (NSUInteger i = 0; i < count; i++) {
NSLog(#"element %d: %#", i, [ones objectAtIndex: i]);
}
This is not losing the encoding, try to add the strings from the nsarray to a UILabel or UITextField and it should be correct
This behavior of writing the Unicode representation happens only in the console when you NSLog

Fast Enumeration error?

Getting a warning saying that:
Collection expression type 'NSString *' may not respond to 'countByEnumeratingWithState:objects:count'
when trying to run the following code:
NSString *proper = [NSString stringWithContentsOfFile:#"usr/share/dict/propernames" encoding:NSUTF8StringEncoding error:NULL];
for (NSString *i in proper){
NSLog(#"Item>%#", i);
}
When I run the program I don't get any output from the NSLog statement. Anyone run into this?
The compiler warning is trying to tell you that you cannot iterate over an NSString using a for ... in ... loop. It is further trying to say than the reason for this is that an NSString is not a valid "Collection" type. Your valid "Collection" types are things like NSArray, NSSet, and NSDictionary.
So if your file is supposed to contain structured data, you should parse it into something more useful than a flat NSString. Something like this may give a better result:
NSString* temp = [NSString stringWithContentsOfFile:#"usr/share/dict/propernames" encoding:NSUTF8StringEncoding error:NULL];
NSArray* proper = [temp componentsSeparatedByString:#"\n"];
for (NSString* i in proper){
NSLog(#"Item>%#", i);
}
That will print each line in the file. This assumes, of course, that your input file has one entry per line. If it is structured some other way, then you will have to parse it differently.
After you load the file, split it into lines with componentsSeparatedByString: .
NSArray *lines = [proper componentsSeparatedByString:#"\n"]; // Use the correct line ending character here
for (NSString *i in lines) {
NSLog(#"item> %#", i);
}
This is a clear mistake u have here.
NSString* is a string object and is not a collection of characters as the string object known in C++ which is a character array.
for-in Loop need a collection to iterate within. like NSArray or NSSet.

Resources