stringByReplacingOccurrencesOfString function - ios

I am new to ios development.
NSString *newString2 = [aString stringByReplacingOccurrencesOfString:#"1," withString:#""];
My problem is i do not know how to check for any number i.e. stringByReplacingOccurrencesOfString:#"anyInt," where any Int is any integer number from 1 to N.
Thanks in advance!

Using regular expressions is the best solution:
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[1-9]" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
Check official NSRegularExpression documentation, there is also a good tutorial here

A regular expression is probably the easiest solution. Whether you want to remove just single digits or multiple digits, a regular expression can help.
NSString *aString = #"Apple 10, Banana 3, Carrot 5, Durian 42, Eggplant 4,";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[0-9]+," options:0 error:NULL];
NSString *newString = [regex stringByReplacingMatchesInString:aString options:0 range:NSMakeRange(0, [aString length]) withTemplate:#""];
NSLog(#"%#", newString);
// result should be "Apple Banana Carrot Durian Eggplant "
Regular expressions may seem overwhelming or difficult to understand at first, but it is only because they can be very powerful for searching and replacing text. Have a look at the overview section of the NSRegularExpression documentation for more information.

For nos in first part greater than 0, second part is shown. For 0 in first part, -- is shown.
Try the below code,
NSString * aString = #"1,10";
NSString *newString2;
NSArray *items = [aString componentsSeparatedByString:#","];
if([[items objectAtIndex:0] integerValue]>0)
newString2 = [items objectAtIndex:1];
else
newString2 = #"--";

Just these two lines to remove all numbers from a string.
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
NSString *newString = [[tempstr componentsSeparatedByCharactersInSet: numbers] componentsJoinedByString:#""];

If you want to check the range and then you want to replace then use below api:-
- (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement

why you want to check the existence of the Integer because ultimate you'll replace it with ''. So just use the below line
NSString *newString2 = [aString stringByReplacingOccurrencesOfString:[NSString StringWithFormat:#"%d", anyInt], withString:#""];
Above line will fulfill your requirement.

Related

SubString from existing string iOS

I have two strings as followed:
NSString *newStr = #"143.2a";
NSString *expression = #"^([0-9]*)(\\.([0-9]{0,10})?)?$";
I want to substring "newStr" such as all my characters in "expression" should be present after subString. Like
NSString * extractedString = #"143.2";
(except all alphabets and symbols other than single'.')
How shall I do this?
First of all, your regex pattern won't extract that string.
If you want to check for one or more digits followed be a dot followed be one or more digits the pattern is supposed to be
NSString *expression = #"\\d+\\.\\d+";
To extract the string use the NSRegularExpression class as suggested by Larme.
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:0 error:nil];
NSTextCheckingResult *firstMatch = [regex firstMatchInString:newStr options:0 range:NSMakeRange(0, newStr.length)];
if (firstMatch) {
NSString *extractedString = [newStr substringWithRange:firstMatch.range];
NSLog(#"%#", extractedString);
} else {
NSLog(#"Not Found");
}

Delete occurances at the end of a string - iOS

Say you have a NSString *testString = #"Abcd!!!!";, note the four exclamation marks, how can I delete all exclamation marks as efficiently as possible?
The exclamation marks can be any number of amount, and can only be deleted if they're in consecutive trailing order.
One example might be:
NSString *testString = #"ABC!D!!!!!";
The result would then be:
NSString *result = #"ABC!D";
Since you don't know how many ! you'll be removing from the string, you could do it with a regular expression.
NSString *string = #"ABC!D!!!!!";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"!+$" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
NSLog(#"%#", modifiedString);
Regex aren't always the most efficient way to solve these sorts of problems, but in this case, I don't think there would be a measurable gain doing it another way.

Remove "?" from NSString IOS

I am trying to remove all symbols from a string, it works fine with below code for all symbols except "?".
NSString *newString = self.titleString;
NSArray *characters = #[#"<", #"!", #"#", #"#", #"$", #"%", #"^", #"&", #"*", #"(", #")", #",", #"_", #"+", #"|", #">", #"?", #" "];
for (NSString *str in characters) {
newString = [newString stringByReplacingOccurrencesOfString:str withString:#""];
}
You can use stringByReplacingOccurrencesOfString with the regular expression option, NSRegularExpressionSearch:
NSString *output = [input stringByReplacingOccurrencesOfString:#"[<>!##$%^&*(),_+?| ]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [input length])];
You can also take advantage of other regular expression features, e.g. replace all non-letter characters:
NSString *output = [input stringByReplacingOccurrencesOfString:#"\\P{L}" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [input length])];
or not A-Z:
NSString *output = [input stringByReplacingOccurrencesOfString:#"[^a-zA-Z]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [input length])];
It just depends upon precisely what you're trying to achieve.
You can remove all characters in a single call using NSRegularExpression:
NSString *string = self.titleString;
NSError *error = nil;
// Prepare the regular expression that matches any of your characters
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[<>!##$%^&*(),_+?| ]"
options:NSRegularExpressionCaseInsensitive
error:&error];
// Replace all matches with an empty string
string = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
You have to escape the ? like that: "\?". Otherwise it won't work properly. ? only means in regex stands for 0 or 1 occurences and so you have to say to objective-c that it is a real char you want to test.
If this is for editing user text you might want to consider using a union of more than one NSCharacterSet - this will help it be more language-friendly when you localize/internationalize your app.
NSString *myInputText = #"asd;jkfhals#$%^%$&1asldiguhd";
NSCharacterSet *nonAlphanumeric = [[NSMutableCharacterSet alphanumericCharacterSet] invert];
NSArray *parts = [myInputText componentsSeparatedByCharactersInSet:nonAlphanumeric];
NSArray *mySafeOutputText = [parts componentsJoinedByString:#""];
It's a little non-intuitive to use the components method, but unfortunately Apple doesn't provide a stringByReplacingCharactersInSet: method. :(

how to replace many occurrences of comma by single comma

Earlier I had string as 1,2,3,,5,6,7
To replace string, I used stringByReplacingOccurrencesOfString:#",," withString:#",", which gives output as 1,2,3,5,6,7
Now I have string as below.
1,2,3,,,6,7
To replace string, I used stringByReplacingOccurrencesOfString:#",," withString:#",", which gives output as 1,2,3,,6,7
Is there way where I can replace all double comma by single comma.
I know I can do it using for loop or while loop, but I want to check is there any other way?
for (int j=1;j<=100;j++) {
stringByReplacingOccurrencesOfString:#",," withString:#","]]
}
NSString *string = #"1,2,3,,,6,7";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#",{2,}" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#","];
NSLog(#"%#", modifiedString);
This will match any number of , present in the string. It's future proof :)
Not the perfect solution, but what about this
NSString *string = #"1,2,3,,,6,7";
NSMutableArray *array =[[string componentsSeparatedByString:#","] mutableCopy];
[array removeObject:#""];
NSLog(#"%#",[array componentsJoinedByString:#","]);

Filter new line from array of email strings

I'm trying to send emails to a list that I get from a server which is an array of emails whose output is in this format
(
"john#gmail.com\n",
"katebell#gmail.com\n"
"\nakhil#gmail.com",
"mary#gmail.com",
"timcorb\n#gmail.com
)
Now as you can see some emails have newline characters in between and those emails doesnt get sent. I'm trying to find an efficient way to filter out those newlines, my current approach is to loop through all emails and check for newline in each email and if newline exist replace it with a null string. Is there a better way to do this or should I just stick with that? Also Will my current approach cause any issues in any other scenarios?
One way you can try using NSRegularExpression like this below :-
NSArray *array=#[#"john#gmail.com\n",#"katebell#gmail.com\n",#"\nakhil#gmail.com",#"mary#gmail.com",#"timcorb\n#gmail.com"];
NSString *string =[array componentsJoinedByString: #","];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\n" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
NSLog(#"%#",modifiedString);
Output:-
john#gmail.com,katebell#gmail.com,akhil#gmail.com,mary#gmail.com,timcorb#gmail.com
try something like this
NSString *fileName = #"\ntest\n";
fileName = [fileName stringByReplacingOccurrencesOfString:#"\n" withString:#""];
eg.
NSString * str = #"timcorb\n#gmail.com";
str = [str stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSLog(#"%#",str);
it will Log 2014-01-10 01:01:00.256 demo[26220] timcorb#gmail.com
You can use the below code for replacing characters in a string.
NSString *email = #"\nakhi\nl#gmail.com";
NSString *actualEmail = [email stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSMutableArray* emailArray = [[NSMutableArray alloc] init];
for (int _index = 0; _index < [yourArray count]; _index++) {
[emailArray addobject:[[yourArray objectAtIndex:_index] stringByReplacingOccurrencesOfString:#"\n" withString:#""]];
}
This will give you your email array

Resources