Craig
Craig

Reputation: 1085

changing a character to a different character in a text field

I want to make a de coding type of app, where you have a code "a=z, b=y, c=x" and when a user puts a jumble of letters in the text field it will de-code it for them. For example. I put in "a b c" and when I click a button it will display in another text field "z y x".

I have tried using Regex like this:

NSString *inputFieldContents = inputField.text; // Suppose it's "Hello, zyxw!";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"zyxw" options:NSRegularExpressionCaseInsensitive error:NULL];

NSRange range = NSMakeRange (0, [inputFieldContents length]);
NSString *res = [regex stringByReplacingMatchesInString:inputFieldContents options:0 range:range withTemplate:@"abcd"];
NSLog(@"%@", res);

But this will only give me the decoded message if the letters zyxw are inputed. If I enter wxyz, it won't give me dcba like I would like it to.

Does anybody have any ideas of how to do this?

Thanks!

Upvotes: 1

Views: 86

Answers (1)

justin
justin

Reputation: 104708

you could simply replace strings within a mutable string using:

-[NSMutableString replaceOccurrencesOfString:withString:options:range:].

and if your case is very basic, you may favor:

-[NSString stringByReplacingOccurrencesOfString:withString:]


Update - so one way to approach this would be:

NSMutableString * str = [inputField.text mutableCopy];

enum { NumSubstitutions = 4 };
NSString * const sought[NumSubstitutions] = { @"z", @"y", @"x", @"w" };
NSString * const replacements[NumSubstitutions] = { @"a", @"b", @"c", @"d" };

for (NSUInteger i = 0; i < NumSubstitutions; ++i) {
    [str replaceOccurrencesOfString:sought[i]
                         withString:replacements[i]
                            options:NSCaseInsensitiveSearch
                              range:NSMakeRange(0, inputFieldContents.length)];
}

return [str copy];

Upvotes: 2

Related Questions