Remove unallowed characters from NSString - objective-c

I want to allow only specific characters for a string.
Here's what I've tried.
NSString *mdn = #"010-222-1111";
NSCharacterSet *allowedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"+0123456789"];
NSString *trimmed = [mdn stringByTrimmingCharactersInSet:[allowedCharacterSet invertedSet]];
NSString *replaced = [mdn stringByReplacingOccurrencesOfString:#"-" withString:#""];
The result of above code is as below. The result of replaced is what I want.
trimmed : 010-222-1111
replaced : 0102221111
What am I missing here? Why doesn't invertedSet work?
One more weird thing here. If I removed the invertedSet part like
NSString *trimmed = [mdn stringByTrimmingCharactersInSet:allowedCharacterSet];
The result is
trimmed : -222-
I have no idea what makes this result.

stringByTrimmingCharactersInSet: only removes occurrences in the beginning and the end of the string. That´s why when you take inverted set, no feasible characters are found in the beginning and end of the string and thus aren't removed either.
A solution would be:
- (NSString *)stringByRemovingCharacters:(NSString*)str inSet:(NSCharacterSet *)characterSet {
return [[str componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:#""];
}

stringByTrimmingCharactersInSet is only removing chars at the end and the beginning of the string, which results in -222-. You have to do a little trick to remove all chars in the set
NSString *newString = [[origString componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:#""];

Related

How to Trim special Characters in a String in Objective c

I want to trim the occurence of special characters in a string
String has :
prevs: Case Number
____________________
In this i want to remove -------- this dash from this string .I have tried like this :
NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:#"-"];
NSString *stringNew = [[previousString2 componentsSeparatedByCharactersInSet:trim] componentsJoinedByString:#""];
Thanks in Advance!
Try This:
NSString *stringWithoutDash = [yourString stringByReplacingOccurrencesOfString:#"-" withString:#""];
NSString *trimedString = [myString stringByReplacingOccurrencesOfString:#"-" withString:#""];
Use regular expression, the pattern [\\s_]{4,} searches for 4 and more whitespace or underscore characters.
NSString *trimmedString = [previousString2 stringByReplacingOccurrencesOfString:#"[\\s_]{4,}" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, previousString2.length)];
If the underscore characters are really dashes reaplace the character in the pattern.
You can use below code to remove your special string.
NSString *yourString = #"This is your string with speical character --------";
NSCharacterSet *removedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"--------"];
NSString *finalString = [[yourString componentsSeparatedByCharactersInSet:removedCharacterSet] componentsJoinedByString:#""];
NSLog (#"Your final string : %#", finalString);

Getting digits from an NSString

I have a string like #"(256) 435-8115" or #"256-435-81-15". I need only the digits (this is a phone number). Is this possible? I haven't found an NSString method to do that.
I think there is much simpler way:
-(NSString*)getNumbersFromString:(NSString*)String{
NSArray* Array = [String componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
NSString* returnString = [Array componentsJoinedByString:#""];
return (returnString);
}
Input:
NSString *stringWithPhoneNumber=#"(256) 435-8115";
NSArray *plainNumbersArray=
[stringWithPhoneNumber componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet]invertedSet]];
NSString *plainNumbers = [plainNumbersArray componentsJoinedByString:#""];
NSLog(#"plain number is : %#",plainNumbers);
OutPut:
plain number is : 2564358115
You can use stringByReplacingOccurrencesOfString: withString: to remove characters you don't want such as #"(" with #""

NSString by removing the initial zeros?

How can I remove leading zeros from an NSString?
e.g. I have:
NSString *myString;
with values such as #"0002060", #"00236" and #"21456".
I want to remove any leading zeros if they occur:
e.g. Convert the previous to #"2060", #"236" and #"21456".
Thanks.
For smaller numbers:
NSString *str = #"000123";
NSString *clean = [NSString stringWithFormat:#"%d", [str intValue]];
For numbers exceeding int32 range:
NSString *str = #"100004378121454";
NSString *clean = [NSString stringWithFormat:#"%d", [str longLongValue]];
This is actually a case that is perfectly suited for regular expressions:
NSString *str = #"00000123";
NSString *cleaned = [str stringByReplacingOccurrencesOfString:#"^0+"
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, str.length)];
Only one line of code (in a logical sense, line breaks added for clarity) and there are no limits on the number of characters it handles.
A brief explanation of the regular expression pattern:
The ^ means that the pattern should be anchored to the beginning of the string. We need that to ensure it doesn't match legitimate zeroes inside the sequence of digits.
The 0+ part means that it should match one or more zeroes.
Put together, it matches a sequence of one or more zeroes at the beginning of the string, then replaces that with an empty string - i.e., it deletes the leading zeroes.
The following method also gives the output.
NSString *test = #"0005603235644056";
// Skip leading zeros
NSScanner *scanner = [NSScanner scannerWithString:test];
NSCharacterSet *zeros = [NSCharacterSet
characterSetWithCharactersInString:#"0"];
[scanner scanCharactersFromSet:zeros intoString:NULL];
// Get the rest of the string and log it
NSString *result = [test substringFromIndex:[scanner scanLocation]];
NSLog(#"%# reduced to %#", test, result);
- (NSString *) removeLeadingZeros:(NSString *)Instring
{
NSString *str2 =Instring ;
for (int index=0; index<[str2 length]; index++)
{
if([str2 hasPrefix:#"0"])
str2 =[str2 substringFromIndex:1];
else
break;
}
return str2;
}
In addition to adali's answer, you can do the following if you're worried about the string being too long (i.e. greater than 9 characters):
NSString *str = #"000200001111111";
NSString *strippedStr = [NSString stringWithFormat:#"%lld", [temp longLongValue]];
This will give you the result: 200001111111
Otherwise, [NSString stringWithFormat:#"%d", [temp intValue]] will probably return 2147483647 because of overflow.

How to remove a section of a string using escape character

I have a set of NSString representing the names of the files in a directory. These names are structured this way:
XXXXXXXXX_YYYY_AAAA.ext
All the sections separated by "_" are of variable length and I would only have the first.
How can I separate the first part from the other?
Find the position of the '_' character, then get a substring 0 through that position. Note that substringToIndex: does not include the character at the index position.
NSRange r = [myString rangeOfString:#"_"];
NSString *res = [myString substringToIndex:r.location];
Take a look at the NSString method componentsSeparatedByString:. That will tokenize a string and return you an array. Something like this:
NSArray *array = [#"XXXXXXXXX_YYYY_AAAA.ext" componentsSeparatedByString:#"_"];
NSString *firstToken = [array objectAtIndex:0];
NSArray *array = [yourString componentsSeparatedByString:#"_"];
NSString *Xs = [array objectAtIndex:0];
Try componentsSeparatedByString: under the heading Dividing Strings.
NSString Docs

Remove last character of NSString

I've got some trouble 'ere trying to remove the last character of an NSString.
I'm kinda newbie in Objective-C and I have no idea how to make this work.
Could you guys light me up?
NSString *newString = [oldString substringToIndex:[oldString length]-1];
Always refer to the documentation:
substringToIndex:
length
To include code relevant to your case:
NSString *str = textField.text;
NSString *truncatedString = [str substringToIndex:[str length]-1];
Try this:
s = [s substringToIndex:[s length] - 1];
NSString *string = [NSString stringWithString:#"ABCDEF"];
NSString *newString = [string substringToIndex:[string length]-1];
NSLog(#"%#",newString);
You can see = ABCDE
NSString = *string = #"abcdef";
string = [string substringToIndex:string.length-(string.length>0)];
If there is a character to delete (i.e. the length of the string is greater than 0)
(string.length>0) returns 1, thus making the code return:
string = [string substringToIndex:string.length-1];
If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
(string.length>0) returns 0, thus making the code return:
string = [string substringToIndex:string.length-0];
which prevents crashes.
This code will just return the last character of the string and not removing it :
NSString *newString = [oldString substringToIndex:[oldString length]-1];
you may use this instead to remove the last character and retain the remaining values of a string :
str = [str substringWithRange:NSMakeRange(0,[str length] - 1)];
and also using substringToIndex to a NSString with 0 length will result to crashes.
you should add validation before doing so, like this :
if ([str length] > 0) {
str = [str substringToIndex:[s length] - 1];
}
with this, it is safe to use substring method.
NOTE : Apple will reject your application if it is vulnerable to crashes.
Simple and Best Approach
[mutableString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];