How to count the number of NSString in a NSString - iphone

Hello I try to convert my java function in objective-c for iphone
Java:
public int substrCount(String str, String needle) {
int count = 0;
int index = -needle.length();
while ((index = str.indexOf(needle, index + needle.length())) != -1) {
count++;
}
return count;
}
Iphone:
-(int)substrCount:(NSString *) str withSearch:(NSString *) needle
{
NSRange lastIndex;
lastIndex.length = [str length];
NSInteger count =0;
while(lastIndex.length != -1){
lastIndex = [str rangeOfString:needle options:NSCaseInsensitiveSearch range:lastIndex];
//lastIndex = str.indexOf(needle,lastIndex);
if( lastIndex.length != -1){
NSLog(#"+1");
count ++;
}
}
}
But it's so hard, I don't understand when I can make it.
Maybe there are better solution existing? I don't have found anything :/
Sorry for my bad english !

I'd probably never write this code in production, but You could simply ask:
[[str1 componentsSeparatedByString:str2] count] - 1;
The result of that expression will be an integer representing the number of times str2 was found in str1.
However, the problem with your code is rangeOfString: returns NSNotFound if it can't find the substring, not -1.

Related

Sequential validation on password text Field

How can I validate password for sequential value?
Eg -
if user enters 1326 or "axdf" in password then it is valid.
if use enter 1234 or "abcd" the it is invalid.
I think you can do it this way
NSString *list= #"abcdefghijklmnopqrstuvwxyz";
NSString *password= #"abz"; // Suppose this is your password
NSRange range = [list rangeOfString:password options:NSCaseInsensitiveSearch];
if (range.location == NSNotFound) {
/* Could NOT find password in list, then it is valid */
}
else {
/* Found the password in the list then it is not valid */
}
Similarly you can do it for numbers as well
the easiest way is to use strpos.
$haystack = '01234567890';
function testConsecutive($pHaystack, $pNeedle){
return strpos($pHaystack,$pNeedle) === false?false:true;
}
Oops, I thought that I was answering php code, because that was my filter. This is not php, sorry for that.
In this case, i would suggest you to try matching ASCII value of each character in the string. If the string is sequential, ASCII value of that character should increase by 1
Here is a rough idea how you can implement it, havent tested it but hope it might be helpful.
int prevAsciiCode;
NSString *string = #"12345";
for (int i = 0; i<string.length; i++) {
int asciiCode = [string characterAtIndex:i];
if (asciiCode == prevAsciiCode+1) {
NSLog(#"String invalid");
return;
}
prevAsciiCode = asciiCode;
}
A string is a sequence of chars, each char is represented by is ASCII code, so you can iterate throw the chars of the string and compare each one with its previous int value, for example:
- (BOOL)isSequence:(NSString *)string
{
char previousChar = [string characterAtIndex:0];
int wordLength = [string length];
BOOL isSequence = YES;
for (int i = 0; i < wordLength && isSequence; i++)
{
char currentChar = [string characterAtIndex:i];
if (currentChar != previousChar+1) {
isSequence = NO;
}
previousChar = currentChar;
}
return isSequence;
}

how to add comma to string after every nth character in xcode

my problem is pretty simple. I assign a value to string variable in xcode which looks like this:
ARAMAUBEBABRBGCNDKDEEEFO
and I need it like this:
AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO
The length is different in each variable.
thanx in advance
This function is usefull for numbers that need coma every thousands... which is what I wanted, hope it helps.
//add comas to a a string...
//example1: #"5123" = #"5,123"
//example2: #"123" = #"123"
//example3: #"123123123" = #"123,123,123"
-(NSString*) addComasToStringEvery3chrsFromRightToLeft:(NSString*) myString{
NSMutableString *stringFormatted = [NSMutableString stringWithFormat:#"%#",myString];
for(NSInteger i=[stringFormatted length]-3;i>0;i=i-3) {
if (i>0) {
[stringFormatted insertString: #"," atIndex: i];
}
}
return stringFormatted;
}
Try this:
int num;
NSMutableString *string1 = [NSMutableString stringWithString: #"1234567890"];
num = [string1 length];
for(int i=3;i<=num+1;i++) {
[string1 insertString: #"," atIndex: i];
i+=3;
}
NSString *yourString; // the string you want to process
int len = 2; // the length
NSMutableString *str = [NSMutableString string];
int i = 0;
for (; i < [yourString length]; i+=len) {
NSRange range = NSMakeRange(i, len);
[str appendString:[yourString substringWithRange:range]];
[str appendString:#","];
}
if (i < [str length]-1) { // add remain part
[str appendString:[yourString substringFromIndex:i]];
}
// str now is what your want
This would work well when your string is not very large:
NSString * StringByInsertingStringEveryNCharacters(NSString * const pString,
NSString * const pStringToInsert,
const size_t n) {
NSMutableString * const s = pString.mutableCopy;
for (NSUInteger pos = n, advance = n + pStringToInsert.length; pos < s.length; pos += advance) {
[s insertString:pStringToInsert atIndex:pos];
}
return s.copy;
}
If the string is very large, you should favor to compose it without insertion (append-only).
(define your own error detection)

Better way to handle arrays in Objective-C?

Please let me preface this question with an apology. I am very new to Objective C. Unfortunately, I have a very tight timeline on a project for work and need to get up to speed as fast as possible.
The code below works. I am just wondering if there is a better way to handle this... Maybe something more Cocoa-ish. The entire purpose of the function is to get an ordered list of positions in a string that have a certain value.
I fell back on a standard array for comfort reasons. The NSMutableString that I initially declare is only for testing purposes. Being a complete noob to this language and still wrapping my head around the way Objective C (and C++ I guess) handles variables and pointers, any and all hints, tips, pointers would be appreciated.
NSMutableString *mut = [[NSMutableString alloc] initWithString:#"This is a test of the emergency broadcast system. This is only a test."];
NSMutableArray *tList = [NSMutableArray arrayWithArray:[mut componentsSeparatedByString:#" "]];
int dump[(tList.count-1)];
int dpCount=0;
NSUInteger length = [mut length];
NSRange myRange = NSMakeRange(0, length);
while (myRange.location != NSNotFound) {
myRange = [mut rangeOfString:#" " options: 0 range:myRange];
if (myRange.location != NSNotFound) {
dump[dpCount]=myRange.location;
++dpCount;
myRange = NSMakeRange((myRange.location+myRange.length), (length - (myRange.location+myRange.length)));
}
}
for (int i=0; i < dpCount; ++i) {
//Going to do something with these values in the future... they MUST be in order.
NSLog(#"Dumping positions in order: %i",dump[i]);
}
text2.text = mut;
[mut release];
Thanks again for any replies.
There is not great way to do what you are trying to do. Here is one way:
// locations will be an NSArray of NSNumbers --
// each NSNumber containing one location of the substring):
NSMutableArray *locations = [NSMutableArray new];
NSRange searchRange = NSMakeRange(0,string.length);
NSRange foundRange;
while (searchRange.location < string.length) {
searchRange.length = string.length-searchRange.location;
foundRange = [string rangeOfString:substring options:nil range:searchRange];
if(foundRange.location == NSNotFound) break;
[locations addObject:[NSNumber numberWithInt:searchRange.location]];
searchRange.location = foundRange.location+foundRange.length;
}
This might be a little more streamlined (and faster in terms of execution time, if that matters):
const char *p = "This is a test of the emergency broadcast system. This is only a test.";
NSMutableArray *positions = [NSMutableArray array];
for (int i = 0; *p; p++, i++)
{
if (*p == ' ') {
[positions addObject:[NSNumber numberWithInt:i]];
}
}
for (int j = 0; j < [positions count]; j++) {
NSLog(#"position %d: %#", j + 1, [positions objectAtIndex:j]);
}

Getting NSRange of string between quotations?

I have a string:
He said "hello mate" yesterday.
I want to get an NSRange from the first quotation to the last quotation. So I tried something like this:
NSRange openingRange = [title rangeOfString:#"\""];
NSRange closingRange = [title rangeOfString:#"\""];
NSRange textRange = NSMakeRange(openingRange.location, closingRange.location+1 - openingRange.location);
But I'm not sure how to make it distinguish between the first quote and the second quote. How would I do this?
You could use a regular expression for this:
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"([\"])(?:\\\\\\1|.)*?\\1" options:0 error:&error];
NSRange range = [regex rangeOfFirstMatchInString:myString options:0 range:NSRangeMake(0, [myString length]];
Don't forget to check for errors ;)
You can always use 'rangeOfString:options:range:' for the second one (starting after the 'location' of the first one).
Option 1
- (NSRange)rangeOfQuoteInString:(NSString *)str {
int firstMatch = [str rangeOfString:#"\""].location;
int secondMatch = [str rangeOfString:#"\"" options:0 range:NSMakeRange(firstMatch + 1, [str length] - firstMatch - 1)].location;
return NSMakeRange(firstMatch, secondMatch + 1 - firstMatch);
}
I hope this is right. Done on my phone at dinner. ;-)
One other thing, though, since range of string likely does a similar implementation, why not iterate the 'char' values in the string and look for matches #1 & #2? Could be as fast or faster.
Option 2
- (NSRange)rangeOfQuoteInString:(NSString *)str {
int firstMatch = -1;
int secondMatch = -1;
for (int i = 0; i < [str length]; i = i + 1) {
unichar c = [str characterAtIndex:i];
if (c == '"') {
if (firstMatch == -1) {
firstMatch = i;
} else {
secondMatch = i;
break;
}
}
}
if (firstMatch == -1 || secondMatch == -1) {
// No full quote was found
return NSMakeRange(NSNotFound, 0);
} else {
return NSMakeRange(firstMatch, secondMatch + 1 - firstMatch);
}
}

Character occurrences in a String Objective C

How can I count the occurrence of a character in a string?
Example
String: 123-456-7890
I want to find the occurrence count of "-" in given string
You can simply do it like this:
NSString *string = #"123-456-7890";
int times = [[string componentsSeparatedByString:#"-"] count]-1;
NSLog(#"Counted times: %i", times);
Output:
Counted times: 2
This will do the work,
int numberOfOccurences = [[theString componentsSeparatedByString:#"-"] count];
I did this for you. try this.
unichar findC;
int count = 0;
NSString *strr = #"123-456-7890";
for (int i = 0; i<strr.length; i++) {
findC = [strr characterAtIndex:i];
if (findC == '-'){
count++;
}
}
NSLog(#"%d",count);
int total = 0;
NSString *str = #"123-456-7890";
for(int i=0; i<[str length];i++)
{
unichar c = [str characterAtIndex:i];
if (![[NSCharacterSet alphanumericCharacterSet] characterIsMember:c])
{
NSLog(#"%c",c);
total++;
}
}
NSLog(#"%d",total);
this worked. hope it helps. happy coding :)
int num = [[[myString mutableCopy] autorelease] replaceOccurrencesOfString:#"-" withString:#"X" options:NSLiteralSearch range:NSMakeRange(0, [myString length])];
The replaceOccurrencesOfString:withString:options:range: method returns the number of replacements that were made, so we can use that to work out how many -s are in your string.
You can use replaceOccurrencesOfString:withString:options:range: method of NSString
The current selected answer will fail if the string starts or ends with the character you are checking for.
Use this instead:
int numberOfOccurances = (int)yourString.length - (int)[yourString stringByReplacingOccurrencesOfString:#"-" withString:#""].length;