Alphanumeric in a string - objective-c

I need help with fixing a code.
I need it to look at the first two characters of the subclass. If it is alphanumeric (letters and number) the subclassize=7; if both the first two characters are numeric
subclassize=4.
This is the code:
int startrentex=0;
int rentexsize=0;
//int totalsize=0;
int subclasssize=7;
//int descriptionsize=9;
int currentlength=[enteredText length];
if(appdata.appSettings.BarCodeStyle==0) {
if(currentlength>1){
NSString *str = [enteredText substringWithRange:NSMakeRange(1, 1)];
int testint=[str intValue];
if(![str isEqualToString:#"0"] && testint==0)
subclasssize=7;
else
subclasssize=4;
//a3fs12345hi there
//1B3456712345hi there
}
startrentex=subclasssize;
if(currentlength>subclasssize)
{
BOOL isspace=YES;

I need it to look at the first two characters of the subclass.
If you want to look at characters then use the NSString method - characterAtIndex:. This will return you a value of type unichar - the type of unicode characters in Objective-C.
Once you have your first two characters you can test them.
If it is alphanumeric (letters and number) the subclassize=7; if both the first two characters are numeric subclassize=4
To determine the class of a character you can use NSCharacterSet. This class provides standard sets of characters, e.g. + decimalDigitCharacterSet, and a method to test for membership - characterIsMember:.
With these classes and methods you should be able to quickly solve your problem. You will find full details of these classes and methods in Apple’s documentation.
HTH

Related

How to define a variable string format specifier

I have this line of code
// valueX is a long double (long double is a huge floating point)
NSString *value = [NSString stringWithFormat: #"%.10Lg", valueX];
This format specifier is specifying up to 10 decimal digits but I don't want to hard code this to 10.
I have this variable numberOfDigits that I want to be used to define the number of digits. For those itching to down vote this question, it is not so easy as it seems. I cannot substitute the 10 with %# because %.10Lg is a format specifier by itself.
OK, I can create a bunch of strings like #"%.5Lg", #"%.8Lg", #"%.9Lg"... and switch that, but I wonder if there is another way...
There is, if you read the manual pages for format specifiers. You can replace the precision with *, which means it will get taken from a parameter instead.
int numDigits = 10;
NSString *value = [NSString stringWithFormat:#"%.*Lg", numDigits, valueX];
I couldn't find this in the core foundation reference, but I know that this is written in the man 3 printf man page.
Dietrich's answer is the simplest and therefore best. Note that even if there wasn't a built-in way to specify the number of digits with a parameter you could still have done it by first building your format string and then using it:
- (NSString *) stringFromValue: (long double) value digits: (int) digits; {
//First create a format string. Use "%%" to escape the % escape char.
NSString *formatString =[NSString stringWithFormat: #"%%.%dLg", digits];
return [NSString stringWithFormat: formatString, value];
}

Replacing character within cstring - getting bad access

Is it possible to replace a character from a c string after converting it from NSString via the UTF8string method?
For example take the code below. It is to format a string with particular rule.
- (NSString *)formatString:(NSString *)input {
if (input.length==0) {
return #"";
}
//code to determine rule
....
....
// substitute output format with input characters
if (rule) {
input = [input substringFromIndex:prefix.length];
char *string = (char *)[rule UTF8String];
int repCount = 0;
for (int i=0; i<rule.length; i++) {
if (string[i] == '#') {
if (repCount < input.length)
string[i] = [input characterAtIndex:repCount++];//bad access
else
string[i] = ' ';
}
}
NSMutableString *output = [NSMutableString stringWithCString:string encoding:NSUTF8StringEncoding];
...
... //do something with the output
return output;
} else {
return input;
}
}
Initially string[0] has '#' and it should get replaced with the character in the input. This is not happening.
In a word, NO. That buffer doesn't belong to you so leave it alone.
A couple of issues:
You are casting UTF8String, which returns a const char *, to char *. UTF8String is, by definition, returning a read-only string and you should use it as such. (You really should use casts sparingly, if at all. Certainly never use casts to override const qualifiers for variables.)
If you want to perform this C-string manipulation, you have to copy the string to your own buffer. For example, use getCString or getCharacters methods (but only after you've created a buffer to receive them, and remember to add a character for the NULL terminator).
By the way, you're also returning characterAtIndex, which is a unichar (which can be larger than 8-bits), and using it in your char * buffer (8-bits per character). I'd be wary about mixing and matching those without being very careful. It is best to pick one and stick with it (and unichar offers a little more tolerance for those non-8-bit characters).
Perhaps you check for this earlier, but you're setting string to be those characters after the prefix, and then proceed to check the next rule.length number of characters. But, as far as I can tell, you have no assurances that string actually has that many characters left in it. You should test for that, or else that will also cause problems.
Personally, I'd retire this whole C-string algorithm and employ the appropriate NSString and/or NSMutableString methods to do whatever replacement you wanted, e.g. stringByReplacingCharactersInRange, stringByReplacingOccurrencesOfString, or the equivalent NSMutableString methods, replaceCharactersInRange or replaceOccurrencesOfString.

Concatenating an int to a string in Objective-c

How do I concatenate the int length to the string I'm trying to slap into that array so it is "C10" given length == 10, of course. I see #"%d", intVarName way of doing it used else where. In Java I would of done "C" + length;. I am using the replaceObjectAtIndex method to replace the empty string, "", that I have previously populated the MSMutableArray "board" with. I am getting an error though when I add the #"C%d", length part at the end of that method (second to last line, above i++).
As part of my homework I have to randomly place "Chutes" (represented by a string of format, "C'length_of_chute'", in this first assignment they will always be of length 10 so it will simply be "C10") onto a game board represented by an array.
-(void)makeChutes: (int) length {// ??Change input to Negative number, Nvm.
//??Make argument number of Chutes ??randomly?? across the board.
for(int i = 0; i < length;){
int random = arc4random_uniform(101);
if ([[board objectAtIndex:random] isEqual:#""]) {
//[board insertObject:#"C%d",length atIndex:random];
[board replaceObjectAtIndex:random withObject:#"C%d",length];
i++;
}
}
}
Please ignore the extra and junk code in there, I left it in for context.
In Objective-C the stringWithFormat method is used for formatting strings:
NSString *formattedString = [NSString stringWithFormat:#"C%d", length];
[someArray insertObject:formattedString];
It's often easier to create your formatted string on a line of its own in Objective-C, since as you can see the call can be fairly verbose!

How do I split an NSString by each character in the string?

I have the following code, which works as I expect. What I would like to know if there is an accepted Cocoa way of splitting a string into an array with each character of the string as an object in an array?
- (NSString *)doStuffWithString:(NSString *)string {
NSMutableArray *stringBuffer = [NSMutableArray arrayWithCapacity:[string length]];
for (int i = 0; i < [string length]; i++) {
[stringBuffer addObject:[NSString stringWithFormat:#"%C", [string characterAtIndex:i]]];
}
// doing stuff with the array
return [stringBuffer componentsJoinedByString:#""];
}
As a string is already an array of characters, that seems, ... redundant.
If you really need an NSArray of NSStrings of one character each, I think your way of creating it is OK.
But it appears questionable that your purpose cannot be done in a more readable, safe (and performance-optimized) way. One thing especially seem dangerous to me: Splitting strings into unicode characters is (most of the time) not doing what you might expect. There are characters that are composed of more than one unicode code point. and there are unicode code points that really are more than one character. Unless you know about these (or can guarantee that your input does not contain arbitrary strings) you shouldn’t poke around in unicode strings on the character level.

Empty character in Objective-C

I'm creating some code that will find a space between characters, and use the characters before the space and the ones after it. These characters are stored in a NSString. Here is what I have so far, however, it's not seeing the empty character.
NSString *tempTitle = self.title;
unsigned int indexOfSpace; // Holds the index of the character with the space
unsigned int titleLength = (unsigned int)self.title.length; // Holds the length of the title
for (unsigned int count = 0; count < titleLength; count++)
{
if ([tempTitle characterAtIndex:count] == "") // If the character at the index is blank, store this and stop
{
indexOfSpace == count;
}
else // Else, we keep on rollin'
{
NSLog(#"We're on character: %c", [tempTitle characterAtIndex:count]);
}
}
I've tried nil , empty string ("") and " " but no avail. Any ideas?
Your space character should be in single quotes, not double quotes. Single quotes get you the char type in C. (Double quotes create a string literal, which essentially functions as a char * and will never pass your comparison.)
-[NSString characterAtIndex:] returns a type unichar, which is an unsigned short, so you should be able to compare this directly to a space character ' ', if that's what you want to do.
Note that nil and empty string, are not useful here-- neither are actually characters, and in any case your string will never "contain" these.
You should see also the NSString methods for finding characters in strings directly, e.g. -[NSString rangeOfString:] and its cousins. That prevents you from writing the loop yourself, although those are unfortunately a little syntactically verbose.