Index for character in NSString - iphone

I have NSString *string = #"Helo"; and NSString *editedString = #"Hello";. How find index for changed character or characters (for example here is #"l").

Start going through one string and compare each character with the character at the same index in the other string. The place where the comparison fails is the index of the changed character.

I've written a category on NSString that will do what you want. I've used my StackOverflow username as a postfix on the category method. This is to stop an unlikely potential future collision with a method of the same name. Feel free to change it.
First the interface definition NSString+Difference.h:
#import <Foundation/Foundation.h>
#interface NSString (Difference)
- (NSInteger)indexOfFirstDifferenceWithString_mttrb:(NSString *)string;
#end
and the implementation 'NSString+Difference.m`:
#import "NSString+Difference.h"
#implementation NSString (Difference)
- (NSInteger)indexOfFirstDifferenceWithString_mttrb:(NSString *)string; {
// Quickly check the strings aren't identical
if ([self isEqualToString:string])
return -1;
// If we access the characterAtIndex off the end of a string
// we'll generate an NSRangeException so we only want to iterate
// over the length of the shortest string
NSUInteger length = MIN([self length], [string length]);
// Iterate over the characters, starting with the first
// and return the index of the first occurence that is
// different
for(NSUInteger idx = 0; idx < length; idx++) {
if ([self characterAtIndex:idx] != [string characterAtIndex:idx]) {
return idx;
}
}
// We've got here so the beginning of the longer string matches
// the short string but the longer string will differ at the next
// character. We already know the strings aren't identical as we
// tested for equality above. Therefore, the difference is at the
// length of the shorter string.
return length;
}
#end
You would use the above as follows:
NSString *stringOne = #"Helo";
NSString *stringTwo = #"Hello";
NSLog(#"%ld", [stringOne indexOfFirstDifferenceWithString_mttrb:stringTwo]);

You can use -rangeOfString:. For example, [string rangeOfString:#"l"].location. There are several variants of that method, too.

Related

(# ゚Д゚) is a 5-letter-word. But in iOS, [#"(# ゚Д゚)" length] is 7. Why?

(# ゚Д゚) is a 5-letter-word. But in iOS, [#"(# ゚Д゚)" length] is 7.
Why?
I'm using <UITextInput> to modify the text in a UITextField or UITextView. When I make a UITextRange of 5 character length, it can just cover the (# ゚Д゚) . So, why this (# ゚Д゚) looks like a 5-character-word in UITextField and UITextView, but looks like a 7-character-word in NSString???
How can I get the correct length of a string in this case?
1) As many in the comments have already stated, Your string is made of 5 composed character sequences (or character clusters if you prefer). When broken down by unichars as NSString’s length method does you will get a 7 which is the number of unichars it takes to represent your string in memory.
2) Apparently the UITextField and UITextView are handling the strings in a unichar savvy way. Good news, so can you. See #3.
3) You can get the number of composed character sequences by using some of the NSString API which properly deals with composed character sequences. A quick example I baked up, very quickly, is a small NSString category:
#implementation NSString (ComposedCharacterSequences_helper)
-(NSUInteger)numberOfComposedCharacterSequences{
__block NSUInteger count = 0;
[self enumerateSubstringsInRange:NSMakeRange(0, self.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
NSLog(#"%#",substring); // Just for fun
count++;
}];
return count;
}
#end
Again this is quick code; but it should get you started. And if you use it like so:
NSString *string = #"(# ゚Д゚)";
NSLog(#"string length %i", string.length);
NSLog(#"composed character count %i", [string numberOfComposedCharacterSequences]);
You will see that you get the desired result.
For an in-depth explanation of the NSString API check out the WWDC 2012 Session 215 Video "Text and Linguistic Analysis"
Both ゚ and Д゚ are represented by a character sequence of two Unicode characters (even when they are visually presented as one). -[NSString length] reports the number of Unicode chars:
The number returned includes the individual characters of composed
character sequences, so you cannot use this method to determine if a
string will be visible when printed or how long it will appear.
If you want to see the byte representation:
#import <Foundation/Foundation.h>
NSString* describeUnicodeCharacters(NSString* str)
{
NSMutableString* codePoints = [NSMutableString string];
for(NSUInteger i = 0; i < [str length]; ++i){
long ch = (long)[str characterAtIndex:i];
[codePoints appendFormat:#"%0.4lX ", ch];
}
return codePoints;
}
int main(int argc, char *argv[]) {
#autoreleasepool {
NSString *s = #" ゚Д゚";
NSLog(#"%ld unicode chars. bytes: %#",
[s length], describeUnicodeCharacters(s));
}
}
The output is: 4 unicode chars. bytes: 0020 FF9F 0414 FF9F.
2) and 3): what NJones said.

Checking if an NSString contains base64 data

How can I check to see if an NSString contains base64 data in an if statement? Because base64 encodes the data in a completely random way, I can't search for a phrase within the NSString so instead I will need to check to see if the contents of the string results in a data file.
Here's a category on NSString I created that should work:
#interface NSString (MDBase64Additions)
- (BOOL)isBase64Data;
#end
#implementation NSString (MDBase64Additions)
- (BOOL)isBase64Data {
if ([self length] % 4 == 0) {
static NSCharacterSet *invertedBase64CharacterSet = nil;
if (invertedBase64CharacterSet == nil) {
invertedBase64CharacterSet = [[[NSCharacterSet
characterSetWithCharactersInString:
#"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="]
invertedSet] retain];
}
return [self rangeOfCharacterFromSet:invertedBase64CharacterSet
options:NSLiteralSearch].location == NSNotFound;
}
return NO;
}
#end
If you expect newlines or blank spaces in the data, you could update this method to remove those first (likely NSCharacterSet's +whitespaceCharacterSet).
If there's primarily just one class where you'll be using this category method, you could put this code inside its .m file above that class's #implementation block. If you think you might want to use that category from more than one class, you could create a separate .h & .m pair to contain it (e.g. MDFoundationAdditions.h, MDFoundationAdditions.m), and then import it into those classes.
To use:
NSString *dataString = /* assume exists */;
if ([dataString isBase64Data]) {
}

Uppercase first letter in NSString

How can I uppercase the fisrt letter of a NSString, and removing any accents ?
For instance, Àlter, Alter, alter should become Alter.
But, /lter, )lter, :lter should remains the same, as the first character is not a letter.
Please Do NOT use this method. Because one letter may have different count in different language. You can check dreamlax answer for that. But I'm sure that You would learn something from my answer.
NSString *capitalisedSentence = nil;
//Does the string live in memory and does it have at least one letter?
if (yourString && yourString.length > 0) {
// Yes, it does.
capitalisedSentence = [yourString stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[yourString substringToIndex:1] capitalizedString]];
} else {
// No, it doesn't.
}
Why should I care about the number of letters?
If you try to access (e.g NSMakeRange, substringToIndex etc)
the first character in an empty string like #"", then your app will crash. To avoid this you must verify that it exists before processing on it.
What if my string was nil?
Mr.Nil: I'm 'nil'. I can digest anything that you send to me. I won't allow your app to crash all by itself. ;)
nil will observe any method call you send to it.
So it will digest anything you try on it, nil is your friend.
You can use NSString's:
- (NSString *)capitalizedString
or (iOS 6.0 and above):
- (NSString *)capitalizedStringWithLocale:(NSLocale *)locale
Since you want to remove diacritic marks, you could use this method in combination with the common string manipulating methods, like this:
/* create a locale where diacritic marks are not considered important, e.g. US English */
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en-US"] autorelease];
NSString *input = #"Àlter";
/* get first char */
NSString *firstChar = [input substringToIndex:1];
/* remove any diacritic mark */
NSString *folded = [firstChar stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:locale];
/* create the new string */
NSString *result = [[folded uppercaseString] stringByAppendingString:[input substringFromIndex:1]];
Gonna drop a list of steps which I think you can use to get this done. Hope you can follow through without a prob! :)
Use decomposedStringWithCanonicalMappingto decompose any accents (Important to make sure accented characters aren't just removed unnecessarily)
Use characterAtIndex: to extract the first letter (index 0), use upperCaseString to turn it into capitol lettering and use stringByReplacingCharactersInRange to replace the first letter back into the original string.
In this step, BEFORE turning it into uppercase, you can check whether the first letter is one of the characters you do not want to replace, e.g. ":" or ";", and if it is, do not follow through with the rest of the procedure.
Do a [theString stringByReplacingOccurrencesOfString:#"" withString:#""]` sort of call to remove any accents left over.
This all should both capitalize your first letter AND remove any accents :)
Since iOS 9.0 there is a method to capitalize string using current locale:
#property(readonly, copy) NSString *localizedCapitalizedString;
I'm using this method for similar situations but I'm not sure if question asked to make other letters lowercase.
- (NSString *)capitalizedOnlyFirstLetter {
if (self.length < 1) {
return #"";
}
else if (self.length == 1) {
return [self capitalizedString];
}
else {
NSString *firstChar = [self substringToIndex:1];
NSString *otherChars = [self substringWithRange:NSMakeRange(1, self.length - 1)];
return [NSString stringWithFormat:#"%#%#", [firstChar uppercaseString], [otherChars lowercaseString]];
}
}
Just for adding some options, I use this category to capitalize the first letter of a NSString.
#interface NSString (CapitalizeFirst)
- (NSString *)capitalizeFirst;
- (NSString *)removeDiacritic;
#end
#implementation NSString (CapitalizeFirst)
- (NSString *)capitalizeFirst {
if ( self.length <= 1 ) {
return [self uppercaseString];
}
else {
return [[[[self substringToIndex:1] removeDiacritic] uppercaseString] stringByAppendingString:[[self substringFromIndex:1] removeDiacritic]];
// Or: return [NSString stringWithFormat:#"%#%#", [[[self substringToIndex:1] removeDiacritic] uppercaseString], [[self substringFromIndex:1] removeDiacritic]];
}
}
- (NSString *)removeDiacritic { // Taken from: http://stackoverflow.com/a/10932536/1986221
NSData *data = [NSData dataUsingEncoding:NSASCIIStringEncoding
allowsLossyConversion:YES];
return [[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding];
}
#end
And then you can simply call:
NSString *helloWorld = #"hello world";
NSString *capitalized = [helloWorld capitalizeFirst];
NSLog(#"%# - %#", helloWorld, capitalized);

String matching objective-c

I need to match my string in this way: *myString*
where * mean any substring.
which method should I use?
can you help me, please?
If it's for iPhone OS 3.2 or later, use NSRegularExpressionSearch.
NSString *regEx = [NSString stringWithFormat:#".*%#.*", yourSearchString];
NSRange range = [stringToSearch rangeOfString:regEx options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
}
You can't do an actual search using a * (wildcard character), but you can usually do something that is equivalent:
Equivalent to searching for theTerm*:
if ([theString hasPrefix:#"theTerm"]) {
Equivalent to searching for *theTerm:
if ([theString hasSuffix:#"theTerm"]) {
Or, using the category on NSString shown below, the following is equivalent to searching for *theTerm*:
if ([theString containsString:#"theTerm"]) {
A category is simply a new method (like a function) that we add to class. I wrote the following one because it generally makes more sense to me to think of one string containing another rather than dealing with NSRanges.
// category on NSString
#interface NSString (MDSearchAdditions)
- (BOOL)containsString:(NSString *)aString;
#end
#implementation NSString (MDSearchAdditions)
- (BOOL)containsString:(NSString *)aString {
return [self rangeOfString:aString].location != NSNotFound;
}
#end
If you need something more evolved, try https://github.com/dblock/objc-ngram.

Checking for multiple characters in nsstring

i have a string and i want to check for the multiple characters in this string the following code i working fine for one character how to check for the multiple characters.
NSString *yourString = #"ABCCDEDRFFED"; // For example
NSScanner *scanner = [NSScanner scannerWithString:yourString];
NSCharacterSet *charactersToCount = #"C" // For example
NSString *charactersFromString;
if (!([scanner scanCharactersFromSet:charactersToCount intoString:&charactersFromString])) {
// No characters found
NSLog(#"No characters found");
}
NSInteger characterCount = [charactersFromString length];
UPDATE: The previous example was broken, as NSScanner should not be used like that. Here's a much more straight-forward example:
NSString* string = #"ABCCDEDRFFED";
NSCharacterSet* characters = [NSCharacterSet characterSetWithCharactersInString:#"ABC"];
NSUInteger characterCount;
NSUInteger i;
for (i = 0; i < [yourString length]; i++) {
unichar character = [yourString characterAtIndex:i];
if ([characters characterIsMember:character]) characterCount++;
}
NSLog(#"Total characters = %d", characterCount);
Have a look at the following method in NSCharacterSet:
+ (id)characterSetWithCharactersInString:(NSString *)aString
You can create a character set with more than one character (hence the name character set), by using that class method to create your set. The parameter is a string, every character in that string will end up in the character set.
Also look up NSCountedSet. It can help you keep count of multiple instances of the same character.
For example, from the docs:
countForObject:
Returns the count associated with a given object in the receiver.
- (NSUInteger)countForObject:(id)anObject
Parameters
anObject
The object for which to return the count.
Return Value
The count associated with anObject in the receiver, which can be thought of as the number of occurrences of anObject present in the receiver.