Not that anyone asked, but this also seemed like a case that you could extend NSString to provide extra functionality.
I then found out that actually extending NSString is a really bad idea (but not until I had done so and had this working), so I made a class using composition instead.
Using NS for your own classes isn't a good idea, I was just playing with this.
The result:
NSExtendedString.m:
Code:
#import "NSExtendedString.h"
@implementation NSExtendedString
-(unsigned int) indexOf:(char) searchChar {
NSRange searchRange;
searchRange.location=(unsigned int)searchChar;
searchRange.length=1;
NSRange foundRange = [backingString rangeOfCharacterFromSet:[NSCharacterSet characterSetWithRange:searchRange]];
return foundRange.location;
}
-(NSExtendedString *) initWithString: (NSString *) origString {
if(self = [super init]) {
backingString = [[NSString alloc] initWithString:origString];
}
return self;
}
-(NSExtendedString *) initWithExtendedString: (NSExtendedString *) origString {
if(self = [super init]) {
backingString = [[origString string] copy];
}
return self;
}
-(NSString *) string {
return backingString;
}
@end
NSExtendedString.h:
Code:
#import <Foundation/Foundation.h>
@interface NSExtendedString : NSObject {
NSString *backingString;
}
- (unsigned int) indexOf:(char) searchChar;
-(NSExtendedString *) initWithString: (NSString *) origString;
-(NSExtendedString *) initWithExtendedString: (NSExtendedString *) origString;
-(NSString *) string;
@end
TestNewString.m:
Code:
#import <Foundation/Foundation.h>
#import "NSExtendedString.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSExtendedString *myString = [[NSExtendedString alloc] initWithString:@"Test:string+number-one"];
unsigned int colonPosition = [myString indexOf:':'];
unsigned int plusPosition = [myString indexOf:'+'];
unsigned int minusPosition = [myString indexOf:'-'];
NSLog(@"The position of the first colon is: %u, the position of the first plus is: %u, the position of the first minus is: %u",colonPosition,plusPosition,minusPosition);
NSExtendedString *stringTwo = [[NSExtendedString alloc] initWithExtendedString:myString];
unsigned int plusPositionTwo = [stringTwo indexOf:'+'];
NSLog(@"Testing copy: %u",plusPositionTwo);
[pool release];
return 0;
}
I'm on 10.4, so the proper type for most everything in 10.5 and above would be NSUInteger rather than unsigned int.
-Lee