NSString "Expected ':' before ']' token" error - objective-c

My method aims to extract information on a game level from an input string. The input specifies the size of the 2D array playing area, as well as what items are present at what points in the 2D array.
For example, "4,3 . a,b,c . d,e,f . g,h,i . j,k,l" would comprise 4 columns and 3 rows, to look like this (without the hyphens):
a---d---g---j
b---e---h---k
c---f---i---l
The code works fine until the last line, where I get the error:
"Expected ':' before ']' token".
I've been trying to solve this for a while, so I'll be quite embarrassed if it's something stupid I've missed! Any help would be much appreciated.
-(void)readLevelDataFromString:(NSString*)inputString {
//remove spaces from the input
NSString *tempString = [inputString stringByReplacingOccurrencesOfString:#" " withString:#""];
//make mutable
NSMutableString *levelDataString = [NSMutableString stringWithString:tempString];
//trim first 4 characters, which we don't need
[levelDataString deleteCharactersInRange:NSMakeRange(0, 4)];
//separate whole string into an array of strings, each of which contains information on the particular column
NSArray *levelDataStringColumns = [levelDataString componentsSeparatedByString:#"."];
NSAssert([levelDataStringColumns count] == numColumns, #"In the level data string, the number of columns specified did not match the number of X tiles present.");
NSString *columnString = [[NSString alloc] initWithString:[[levelDataStringColumns] objectAtIndex:0]];
}

You have an extra set of []. You want:
NSString *columnString = [[NSString alloc] initWithString:[levelDataStringColumns objectAtIndex:0]];

You have an extra bracket on the last line, change it to this:
NSString *columnString = [[NSString alloc] initWithString:[levelDataStringColumns objectAtIndex:0]];

Try this for the last line:
NSString *columnString = [[NSString alloc] initWithString:[levelDataStringColumns objectAtIndex:0]];

Related

Copying contents of uint8_t[] into an NSString

I have a uint_8[] array of characters and I'd like to convert it to an NSString but I'm getting NULL back. What's the proper way to convert between these two types?
// Defined else where as:
uint8_t someValue[8];
someValue is not NULL and contains some valid characters
I've tried:
NSLog(#"converted using CString: %#", [NSString stringWithCString:(char const *)someValue encoding:NSUTF8StringEncoding]);
as well as:
NSMutableData *data = [[NSMutableData alloc] init];
[data appendBytes:someValue length:sizeof(someValue)];
converted = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"converted using NSData: %#", converted);
Using:
[NSString stringWithCString:(char const *)someValue encoding:NSUTF8StringEncoding];
only works if there is a null terminator in the someValue array.
Your other solution doesn't work because sizeof(someValue) does not return the number of characters in the array, it returns the size of the uint8_t pointer.
You can use:
NSUInteger len = ... // the actual number of characters in someValue
NSString *str = [[NSString alloc] initWithBytes:someValue length:len encoding:NSUTF8StringEncoding];
Of course this requires that you know how many characters are really in the array.

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
)

How to leave a set number of spaces in NSString?

I have separate text objects for the unchanging portion (i.e. "Bonus Score: (+7%)") and the changing portion (e.g. "247,890"). Since they're separate, I want to leave space in the unchanging portion to display the number.
What I first tried was:
NSString* numberString = #"247,890";
NSString* blankScore = [#"" stringByPaddingToLength:[numberString length] withString: #" " startingAtIndex:0];
NSString* baseDisplay = [NSString stringWithFormat:#"BONUS SCORE: %# (+7%%)", blankScore];
'blankScore' was the correct length, but the resulting baseDisplay seemed to trim the spaces around where blankScore would be, making it too small of a space for the displayed number.
Next I tried another way of creating blankScore:
NSString* blankScore = [numberString stringByReplacingCharactersInRange:NSMakeRange(0, [numberString length]) withString:#" "];
But this returned a blankScore of length 1.
Am I understanding these NSString methods incorrectly? I checked the docs, and it seems like my understanding of these methods aligns with what's written there, but I still don't understand why I can't get my baseDisplay to have the correct number of spaces.
Have you printed blankScore on the console using NSLog? Actually your string is correct, but the output is trimmed at end of lines - this is why you see it as described.
#H2CO3 is on to the right solution. You should be using:
NSString *baseDisplay = [NSString stringWithFormat:#"BONUS SCORE: %# (+7%%)", numberString];
To make this work even better, you may want to consider an NSNumberFormatter to correctly format the changing part before inserting it into the baseDisplay object. Something like this:
NSNumber *changingNumber = [NSNumber numberWithDouble:247890];
NSNumberFormatter *correctFormat = [[NSNumberFormatter alloc] init];
[correctFormat setNumberStyle:NSNumberFormatterDecimalStyle];
[correctFormat setHasThousandSeparators:YES];
[correctFormat setUsesGroupingSeparator:YES];
NSString *numberString = [correctFormat stringFromNumber:changingNumber];
NSString *baseDisplay = [NSString stringWithFormat:#"BONUS SCORE: %# (+7%%)", numberString];
This way no matter what number you throw at it, it will correctly display "1,234,456" or "34,567", whatever.
EDIT:
Based on the comments to my answer you will need to use:
stringByPaddingToLength:withString:startingAtIndex:
It should look something like this:
NSString *templateString = #"BONUS SCORE:";
NSString *templateString2 = #"(+7%%)";
NSUInteger baseStringLength = [templateString length] + [numberString length];
NSString *spacedString = [templateString stringByPaddingToLength:baseStringLength withString:#" " startingAtIndex:0];
NSString *baseDisplay = [NSString stringWithFormat:#"%#%#", spacedString, templateString2];

How to remove a section of a string using escape character

I have a set of NSString representing the names of the files in a directory. These names are structured this way:
XXXXXXXXX_YYYY_AAAA.ext
All the sections separated by "_" are of variable length and I would only have the first.
How can I separate the first part from the other?
Find the position of the '_' character, then get a substring 0 through that position. Note that substringToIndex: does not include the character at the index position.
NSRange r = [myString rangeOfString:#"_"];
NSString *res = [myString substringToIndex:r.location];
Take a look at the NSString method componentsSeparatedByString:. That will tokenize a string and return you an array. Something like this:
NSArray *array = [#"XXXXXXXXX_YYYY_AAAA.ext" componentsSeparatedByString:#"_"];
NSString *firstToken = [array objectAtIndex:0];
NSArray *array = [yourString componentsSeparatedByString:#"_"];
NSString *Xs = [array objectAtIndex:0];
Try componentsSeparatedByString: under the heading Dividing Strings.
NSString Docs

Get a string with ascii code objective-c

I have a ascii code, for the letter 'a', and I want to get a string by its ascii code, is it possible with NSString?
This could also work:
NSString *foo = [NSString stringWithFormat:#"%c", 97];
Didn’t test it.
If you mean you have a byte that represents an ASCII-encoded character and you want to make a string out of it, NSString has an initializer just for that.
char characterCodeInASCII = 97;
NSString *stringWithAInIt = [[NSString alloc] initWithBytes:&characterCodeInASCII length:1 encoding:NSASCIIStringEncoding];