Remove Non-English Characters from NSString (Obj-C) - iphone

I have NSString like
Aavkar Complex, Opposite Gurukul, Drive-in Road, Ahmedabad,
àªà«àªàª°àª¾àª¤, India
so I want to consider only english characters and without
english characters are from above string so please give me any idea.
Thanks in advance.

Here is a little dirty example:
NSString *test = #"Olé, señor!";
NSMutableString *asciiCharacters = [NSMutableString string];
for (NSInteger i = 32; i < 127; i++) {
[asciiCharacters appendFormat:#"%c", i];
}
NSCharacterSet *nonAsciiCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:asciiCharacters] invertedSet];
test = [[test componentsSeparatedByCharactersInSet:nonAsciiCharacterSet] componentsJoinedByString:#""];
NSLog(#"%#", test); // Prints #"Ol, seor!"

try this:-
NSString *emailRegEx = #"[A-Za-z]";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
//Valid email address
NSString *textString=#"gagdaksdhaksdhaskdhasldhasldalasàªà«àªàª°àª¾àª¤dhwheqweuqweuqwe";
NSString *textFinalString=#"";
for (int i=0; i<[textString length]; i++) {
NSString *text2string=[textString substringWithRange:NSMakeRange(i,1)];
NSLog(#"%#",text2string);
if ([emailTest evaluateWithObject:text2string] == YES)
{
NSLog(#"yesenglishCharacter");
textFinalString=[textFinalString stringByAppendingString:text2string];
}
else {
NSLog(#"noenglishCharacter");
}
}
NSLog(#"textFinalString%#",textFinalString);

Here is some sample code using NSRange's to do this for a textfield, although the code should be easily adaptable to use for an array of NSString's. Hope that Helps!

Related

Compare two strings and remove common elements

I have two comma seperated NSString's & I want to remove the similar characters from first string only.
ex. str1 = 0,1,2,3
str2 = 1,2.
output -> str1 = 0,3 and str2 = 1,2.
I have one option that, seperate both the string with comma seperated values in a array. But it requires two NSArray's & apply loop and then remove the common elements, but it is very tedious job.
So I want some simple & proper solution which avoid the looping.
kindly help me to sort out this.
Try this one:
No loop is required!!!
You have got all the required APIs.
NSString *str1=#"0,1,2,3";
NSString *str2=#"1,2";
NSMutableArray *arr1=[[NSMutableArray alloc]initWithArray:[str1 componentsSeparatedByString:#","]];
[arr1 removeObjectsInArray:[str2 componentsSeparatedByString:#","]];
NSLog(#"arr1 %#",arr1);
/*
NSMutableString *finalString=[NSMutableString new];
for (NSInteger i=0; i<[arr1 count]; i++) {
NSString *str=[arr1 objectAtIndex:i];
[finalString appendString:str];
if (i!=[arr1 count]-1) {
[finalString appendString:#","];
}
}
*/
NSString *finalString=[arr1 componentsJoinedByString:#","];
NSLog(#"finalString %#",finalString);
Something like that ?
NSString *string = #"0,1,2,3";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self like '1' OR self like '2'"];
NSLog(#"%#",[[string componentsSeparatedByString:#","] filteredArrayUsingPredicate:predicate]);
id str1=#"aa,ab,ac,cd,ce,cf";
id str2=#"aa,ac,cd,cf";
//no ab and no ce
id cmps1 = [str1 componentsSeparatedByString:#","];
id cmps2 = [str2 componentsSeparatedByString:#","];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"NOT SELF IN %#", cmps2];
NSArray *final = [cmps1 filteredArrayUsingPredicate:predicate];
id str = [final componentsJoinedByString:#","];
NSLog(#"%#", str);
The only solution that I can think of would be this:
NSMutableArray* arr1 = [str1 componentsSeparatedByString:#","] mutableCopy];
NSArray* arr2 = [str2 componentsSeparatedByString:#","];
for (NSString* str in arr2) {
[arr1 removeObject:str];
}
NSString* newString1 = [arr1 componentsJoinedByString:#","];
Is this what you tried? If "str1" looks something like "1,1,2,2,2", then you might have some more work to do here to get rid of the duplicates. But that's basically it.

Issue with replacing special characters

Im having a issue with removing special characters from the string .I used the following code.But dint work.Please suggest me better logic
- (NSString *)trimmedReciString:(NSString *)stringName
{
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"-/:;()$&#\".,?!\'[]{}#%^*+=_|~<>€£¥•."];
for (int i = 0; i < [stringName length]; i++) {
unichar c = [stringName characterAtIndex:i];
if ([myCharSet characterIsMember:c]) {
NSLog(#"%#",[NSString stringWithFormat:#"%c",[stringName characterAtIndex:i]]);
stringName = [stringName stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"%c",[stringName characterAtIndex:i]] withString:#""];
}
}
return stringName;
}
NSString *s = #"$$$hgh$g%k&fg$$tw/-tg";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"-/:;()$&#\".,?!\'[]{}#%^*+=_|~<>€£¥•."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
NSLog(#"String is: %#", s);
Try this...
NSString *unfilteredString = #"!##$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
NSLog (#"Result: %#", resultString);
Try starting from the end of the string and work backwards instead of going from front to back, since you're likely to accidentally (and unintentionally) skip characters when the previous character gets deleted.

Convert String into special - splitting an NSString

I have a string like: "mocktail, wine, beer"
How can I convert this into: "mocktail", "wine", "beer"?
the following gives you the desired result:
NSString *_inputString = #"\"mocktail, wine, beer\"";
NSLog(#"input string : %#", _inputString);
NSLog(#"output string : %#", [_inputString stringByReplacingOccurrencesOfString:#", " withString:#"\", \""]);
the result is:
input string : "mocktail, wine, beer"
output string : "mocktail", "wine", "beer"
You need to use:
NSArray * components = [myString componentsSeparatedByString: #", "];
NSString *string = #"mocktail, wine, beer";
//remove whitespaces
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//get array of string
NSArray *array = [trimmedString componentsSeparatedByString:#","];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (NSString *trimmedString in array) {
NSString *newString = [NSMutableString stringWithFormat:#"'%#'", trimmedString];
[newArray addObject:newString];
}
//merge new strings
NSString *finalString = [NSString stringWithFormat:#"%#", [newArray objectAtIndex:0]];
for (NSInteger i = 1; i < [newArray count]; i++) {
finalString = [NSString stringWithFormat:#"%#, %#", finalString, [newArray objectAtIndex:i]];
}
Without knowing spesifically about iOS or objective-c, I assume you could use a split function.
In almost any higher level programming language there is such a function.
Try:
Objective-C split
This gets you an array of Strings. You can then practically do with those what you want to do, e.g. surrounding them with single quotes and appending them back together. :D

NSString to NSArray

I want to split an NSString into an NSArray. For example, given:
NSString *myString=#"ABCDEF";
I want an NSArray like:
NSArray *myArray={A,B,C,D,E,F};
How to do this with Objective-C and Cocoa?
NSMutableArray *letterArray = [NSMutableArray array];
NSString *letters = #"ABCDEF𝍱क्";
[letters enumerateSubstringsInRange:NSMakeRange(0, [letters length])
options:(NSStringEnumerationByComposedCharacterSequences)
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[letterArray addObject:substring];
}];
for (NSString *i in letterArray){
NSLog(#"%#",i);
}
results in
A
B
C
D
E
F
𝍱
क्
enumerateSubstringsInRange:options:usingBlock: available for iOS 4+ can enumerate a string with different styles. One is called NSStringEnumerationByComposedCharacterSequences, what will enumerate letter by letter but is sensitive to surrogate pairs, base characters plus combining marks, Hangul jamo, and Indic consonant clusters, all referred as Composed Character
Note, that the accepted answer "swallows" 𝍱and breaks क् into क and ्.
Conversion
NSString * string = #"A B C D E F";
NSArray * array = [string componentsSeparatedByString:#" "];
//Notice that in this case I separated the objects by a space because that's the way they are separated in the string
Logging
NSLog(#"%#", array);
This is what the console returned
NSMutableArray *chars = [[NSMutableArray alloc] initWithCapacity:[theString length]];
for (int i=0; i < [theString length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%C", [theString characterAtIndex:i]];
[chars addObject:ichar];
}
This link contains examples to split a string into a array based on sub strings and also based on strings in a character set. I hope that post may help you.
here is the code snip
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%c", [myString characterAtIndex:i]];
[characters addObject:ichar];
}
Without loop you can use this:
NSString *myString = #"ABCDEF";
NSMutableString *tempStr =[[NSMutableString alloc] initWithString:myString];
if([myString length] != 0)
{
NSError *error = NULL;
// declare regular expression object
NSRegularExpression *regex =[NSRegularExpression regularExpressionWithPattern:#"(.)" options:NSMatchingReportCompletion error:&error];
// replace each match with matches character + <space> e.g. 'A' with 'A '
[regex replaceMatchesInString:tempStr options:NSMatchingReportCompletion range:NSMakeRange(0,[myString length]) withTemplate:#"$0 "];
// trim last <space> character
[tempStr replaceCharactersInRange:NSMakeRange([tempStr length] - 1, 1) withString:#""];
// split into array
NSArray * arr = [tempStr componentsSeparatedByString:#" "];
// print
NSLog(#"%#",arr);
}
This solution append space in front of each character with the help of regular expression and uses componentsSeparatedByString with <space> to return an array
Swift 4.2:
String to Array
let list = "Karin, Carrie, David"
let listItems = list.components(separatedBy: ", ")
Output : ["Karin", "Carrie", "David"]
Array to String
let list = ["Karin", "Carrie", "David"]
let listStr = list.joined(separator: ", ")
Output : "Karin, Carrie, David"
In Swift, this becomes very simple.
Swift 3:
myString.characters.map { String($0) }
Swift 4:
myString.map { String($0) }

convert a char to string

my code works great until know and, if I put a double digit number into the text field (like 12) nslog returns 2 single digit numbers (like 1 and 2). Now I need to put these 2 single digit numbers into 2 strings. can somebody help me. thanks in advance.
NSString *depositOverTotalRwy = [NSString stringWithFormat:#"%#", [deposit text]];
NSArray *components = [depositOverTotalRwy
componentsSeparatedByString:#"/"];
NSString *firstThird = [components objectAtIndex:0];
for(int i = 0; i < [firstThird length]; i++)
{
char extractedChar = [firstThird characterAtIndex:i];
NSLog(#"%c", extractedChar);
}
You should be able to use -stringWithFormat:.
NSString *s = [NSString stringWithFormat:#"%c", extractedChar];
EDIT:
You can store them in an array.
NSMutableArray *digits = [NSMutableArray array];
for ( int i = 0; i < [s length]; i++ ) {
char extractedChar = [s characterAtIndex:i];
[digits addObject:[NSString stringWithFormat:#"%c", extractedChar]];
}
Try to print the value of firstThird using NSLog(), see what it exactly hold, you code seem correct,
Use characterAtIndex function for NSString to extract a character at known location
- (unichar)characterAtIndex:(NSUInteger)index
Use as below
NSString *FirstDigit = [NSString stringWithFormat:#"%c", [myString characterAtIndex:0]];
NSString *SecondDigit = [NSString stringWithFormat:#"%c", [myString characterAtIndex:1]];