Help me find the same, tried searching many questions all I found was to check if the string contains a special character, but I want to find the number of special characters in a string in objective - c
NSString *abcd = #",;ab/bn']jkfg\";
NSString specialCharacterString = #"!~`##$%^&-+();:={}[],.<>?\/\"\'";
int count = 0;
for (NSUInteger i=0;i<[abcd length];i++){
for(NSUInteger j=0;j<[specialCharacterString length];j++){
if ([abcd characterAtIndex:i]==[specialCharacterString characterAtIndex:j]){
NSLog(#"found: %d", i);
count++;
}
}
Related
I want to count how many number of zero(0) before numeric number. Because I need to save those number which is present before numeric.
Exam:- suppose I have a number 0000102. So I want to calculate how many zero(0) before numeric start. In this exam we are see here is 4 zero's(0) are present. It is possible to calculate this?
for (i=0;i<string.length;i++)
{
if ([[string characterAtIndex:i] intValue] <= 9 || [[string characterAtIndex:i] intValue] > 0 )
{
i++;
}
else
{
numerOfZeros++;
}
}
int count = 0;
NSString *strr = #"0000102";
unichar findC;
for (int i = 0; i<strr.length; i++)
{
findC = [strr characterAtIndex:i];
if (findC == '0')
{
count++;
}
else
break;
}
NSLog(#"%d",count);
Recursive approach for a one liner:
#implementation NSString (category)
- (NSUInteger)zeroPrefixCount
{
return [string hasPrefix:#"0"] ? 1 + [[string substringFromIndex:1] zeroPrefixCount] : 0;
}
#end
This is not an optimal solution, performance-wise, but it's typical of your first days at programming classes.
usage
// x will be 4
NSUInteger x = [#"0000102" zeroPrefixCount];
I recommend you to save this kind of numbers as String itself and no need to further evaluate how many zeros are there rather do a string comparison if needed.
If you really want to count zeros in your number then you can consider converting it to a string and use NSRange and NSString helper methods to get what you want. Similar situation is answered here.
search if NSString contains value
I have an exercise in my Objective-C book in which I must design a program using only the knowledge the book has given me so far to do so. It tells me to use math to do this not any methods from Objective-C.
What I must do is get any integer from the user and then convert each number to a word.
For example if the user enters: 956
The output must then be:
nine
five
six
I am not the best math student and definitely need help here. I can of course use loops of any kind as well as if statements and basic math operators as well as arrays but no built in methods.
I assume that I need to get each digit separated into its own integer variable and then use switch of if statements to then create the strings and display them but cannot successfully do this.
Please help, thanks!
Here's an example I quickly came up with. See the comments in the code below for an explanation.
//Create an array of number strings. They must be in order starting from 0 so the indexes line up
NSArray *numbers = #[#"zero", #"one", #"two", #"three", #"four", #"five", #"six", #"seven", #"eight", #"nine"];
//Create whatever string you're processing
NSString *numString = #"956";
//Loop through the substrings of the number string
while (numString.length > 0) {
//Get the first character in the string
int currentNum = [[numString substringToIndex:1] intValue];
//Print the number. The number string should be at the index of this value in the array
NSLog(#"%#", numbers[currentNum]);
//Remove everything before the first character
numString = [numString substringFromIndex:1];
}
Output:
nine
five
six
Here is a working example using C (one of your tags):
This one makes use of a char *[] (array of C strings) and ascii values of each char...
char *number[]={"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
int main(void)
{
char dig[20];
int len, i;
printf("enter integer: "); //instruction to user
scanf("%s", dig); //read from user
len = strlen(dig);
for(i=0;i<len;i++)
{
if(isdigit(dig[i]))//test to verify good user input (accept only digits)
{
printf("%s\n", number[dig[i]-48]); // 48-57 is range of ASCII values for 0-9
}
}
return 0;
}
Example session:
I have a game that renders the player's nickname.
Normally, I use a nice, styled, bitmap font to render the nickname. However, I only have bitmaps for "normal" characters - A,B,C,...,1,2,3,...!##$%^,.... There are no bitmaps for Chinese, Japanese or whatever other "fancy" characters in any other language.
Trying to render such text with a bitmap will crash because I don't supply such bitmaps. Therefore I decided to detect whether the given string was a "fancy" string, and if that was the case, render the nickname using some generated system font.
How can I detect if a string has fancy characters? My current solution is something like
-(BOOL)isNormalText:(NSString *)text {
char accepted[] = {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()_+{}/\\\"\'?.,"};
for (int i = 0; i < [text length]; ++i) {
char character = [text characterAtIndex:i];
BOOL found = NO;
for (int j = 0; j < 84 && !found; ++j) {
char acceptedChar = accepted[j];
if (character == acceptedChar) {
found = YES;
}
}
if (!found) {
return NO;
}
}
return YES;
}
Which does NOT work, I think. Because a fancy character is not one character - it is a sequence like "\u123".
I have seen a question, in Java, about something similar here: How to check if the word is Japanese or English?
They check if the character value is within the 255 range. But when I do this check in Objective-C, it tells me it is redundant because a char will always be within such range - which makes sense as I imagine the fancy characters to be actually a sequence like "\u123"...
Use an NSCharacterSet, fill it with the characters that you have bitmaps for, then invert the set so that it represents all characters that you don't have. Then use -[NSString rangeOfCharacterFromSet:]. If it returns NSNotFound then the string contains only valid characters.
Just as an example to illustrate what I mean:
- (BOOL) isNormalText:(NSString *) str
{
if (str == nil)
return NO;
NSCharacterSet *allowedChars = [NSCharacterSet characterSetWithCharactersInString:#"ABCDEFG"];
NSCharacterSet *notAllowedChars = [allowedChars invertedSet];
return [str rangeOfCharacterFromSet:notAllowedChars].location == NSNotFound;
}
Use regular expression checking
-(BOOL)isNormalText:(NSString *)text {
NSString * regex = #"(^[A-Za-z0-9]*$)";
NSPredicate * pred = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
BOOL isMatch = [pred evaluateWithObject:text];
return isMatch;
}
I can't find an easy way to generate a one digit sized substring from an NSString. The NSString looks like "(N3)" but I need to store just the number portion "3" in an substring. Using:
NSString *subString = [dis substringFromIndex:2];
returns "3)".
Any ideas?
Well, if the string is one digit and its position is invariant, you could just use:
int Foo(NSString * dis) {
const unichar c = [dis characterAtIndex:2];
assert(isdigit(c) && "not a number");
return c - '0';
}
How do I properly compare a string that I am retrieving from an NSArray to a literal string? So far, I have filled an NSArray up with three blank spaces, " " in one method and now I am trying to replace 10 random indexes in the NSArray with the string "C10", but I don't want to replace what is there unless it is " " still.
Here I created the array of size 100 and filled each spot with 3 blank spaces.
-(void) initBoard{
_board = [board initWithCapacity: 100];
for(int i =0; i < 100; i++){
[_board addObject:#" "];
}
}
Here is the method that I'm having problems with the equality comparison.
-(void)makeChutes: (int) numOfChutes {
//Make argument number of Chutes randomly across the board.
for(int i = 0; i < numOfChutes || i>(-100);){
int random = arc4random_uniform(101);
if ([[_board objectAtIndex:random] isEqual:#" "]) {
NSString *fString = [NSString stringWithFormat:#"C%d", 10];
[_board replaceObjectAtIndex:random withObject:fString];
i++;//Only increments i if 3 blank spaces were at random index..
}
else{//Used to attempt to stop my accidental infinite loop.
i--;
NSLog(#"I, loop, ran %i times.", i);//Attempt failed:-(
}
}
}
I know the above code is a mess. In an attempt to stop the looping I made the i decrement every time it did not meet the for condition and then added an OR condition to my for loop, using ||, to try and stop it after 100 cycles. For some reason the || condition does not stop it from looping even while i is well south of -100.
My first question is how do I properly compare the string stored in the array at index "random" with the literal string of 3 blank spaces? I also tried the method isEqualToString, but it worked the same.
Secondly and less importantly, since I don't need it now, how do I properly code a bi-conditional for loop? I don't get any errors or warnings from Xcode with my for loop syntax and it compiles and runs, so I don't really get why it ignores my second conditions and keeps iterating even while i is < -100.
to know the exist or not and index of it simply use ContainsObject property over NSArray
[array containsObject:#"text"];
int indexOfObject = [array indexOfObject:#"text"];
Use this method for string comparison
[[_board objectAtIndex:random] isEqualToString:#" "]
Modified your code. I think this is what you are looking for
-(void)makeChutes: (int) numOfChutes
{
for(int i = 0; i < numOfChutes ;i++){
int random = arc4random_uniform(101);
if ([[_board objectAtIndex:random] isEqualToString:#" "])
{
[_board replaceObjectAtIndex:random withObject:#"C10"];
i++;
}
}
}
EDIT :
Solution from what you said in comments
-(void)makeChutes: (int) numOfChutes
{
int i=0;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains[cd] ' '"];
NSArray *filteredArray = [_board filteredArrayUsingPredicate:predicate];
int arrayCount=[filteredArray count];
do {
int random = arc4random_uniform(101);
if ([[_board objectAtIndex:random] isEqualToString:#" "])
{
[_board replaceObjectAtIndex:random withObject:#"C10"];
i++;
if (arrayCount == i) {
i=numOfChutes;
}
}
} while (i<numOfChutes);
}
EDIT
From the DOCS
isEqualToString: Returns a Boolean value that indicates whether a
given string is equal to the receiver using a literal Unicode-based
comparison.
(BOOL)isEqualToString:(NSString *)aString Parameters aString The string with which to compare the receiver. Return Value YES if aString
is equivalent to the receiver (if they have the same id or if they are
NSOrderedSame in a literal comparison), otherwise NO.
Discussion The comparison uses the canonical representation of
strings, which for a particular string is the length of the string
plus the Unicode characters that make up the string. When this method
compares two strings, if the individual Unicodes are the same, then
the strings are equal, regardless of the backing store. “Literal” when
applied to string comparison means that various Unicode decomposition
rules are not applied and Unicode characters are individually
compared. So, for instance, “Ö” represented as the composed character
sequence “O” and umlaut would not compare equal to “Ö” represented as
one Unicode character.
My "initBoard" method was broken, causing the "makeChutes" method not to work as expected. Here is the correct initBoard:
-(void) initBoard{
_board = [[NSMutableArray alloc] initWithCapacity:100];
for(int i =0; i < 100; i++){
[_board addObject:#" "];
}
}
And the corrected makeChutes:
-(void)makeChutes: (int) numOfChutes{
//Make argument number of Chutes randomly across the board.
for(int i = 0; i < numOfChutes;){
int random = arc4random_uniform(100);//+1 of max index
if ([[_board objectAtIndex:random] isEqualTo:#" "]){
NSString *fString = [NSString stringWithFormat:#"C%d", 10];
[_board replaceObjectAtIndex:random withObject:fString];
i++;//Only increments i if 3 blank spaces were at random index.
}
}
}