String with allowed chars - iphone

Is there a clean way to get a string containing only allowed characters?
for example:
NSString* myStr = #"a5&/Öñ33";
NSString* allowedChars = #"abcdefghijklmnopqrstuvwxyz0123456789";
NSString* result = [myStr stringWIthAllowedChrs:allowedChars];
result should now be #"a533";

It's not the cleanest, but you could separate the string using a character set, and then combine the resulting array using an empty string.
// Create a character set with every character not in allowedChars
NSCharacterSet *charSet = [[NSCharacterSet characterSetWithCharactersInString:allowedChars] invertedSet];
// Split the original string at any occurrence of those characters
NSArray *splitString = [myStr componentsSeparatedByCharactersInSet:charSet];
// Combine the result into a string
NSString *result = [splitString componentsJoinedByString:#""];

Simple and easy to customize and understand approach:
NSString* myStr = #"a5&/Öñ33";
NSString* allowedChars = #"abcdefghijklmnopqrstuvwxyz0123456789";
NSCharacterSet *set = [[NSCharacterSet characterSetWithCharactersInString:allowedChars] invertedSet];
NSString *result = myStr;
NSRange range = [result rangeOfCharacterFromSet:set];
while (range.location != NSNotFound)
{
result = [result stringByReplacingCharactersInRange:range withString:#""];
range = [result rangeOfCharacterFromSet:set];
}
NSLog(#"%#", result);

One of the simplest-
NSString* result = #"";
for(NSUInteger i = 0; i < [myStr length]; i++)
{
unichar charArr[1] = {[myStr characterAtIndex:i]};
NSString* charString = [NSString stringWithCharacters:charArr length:1];
if([allowedChars rangeOfString:charString].location != NSNotFound)
result = [result stringByAppendingString:charString];
}
return result;

Related

How to random sort a NSString

NSMutableString *str =#"abcdefg123";
I want random the every character to a new String like this #"f1ad2g3be2".
NSMutableString *str1 = [[NSMutableString alloc]initWithString:str];
NSMutableString *str2 = [[NSMutableString alloc] init];
while ([str1 length] > 0) {
int i = arc4random() % [str1 length];
NSRange range = NSMakeRange(i,1);
NSString *sub = [str1 substringWithRange:range];
[str2 appendString:sub];
[str1 replaceOccurrencesOfString:sub withString:#"" options:nil range:range];
}
[str1 release];
str2 is what u want
Quite simple. First you must break up the characters into an array to work with. Then you swap the letters X many times, I choose to do this so every character will be swapped
NSString *str =#"abcdefg123";
int length = str.length;
NSMutableArray *letters = [[NSMutableArray alloc] init];
for (int i = 0; i< length; i++) {
NSString *letter = [NSString stringWithFormat:#"%c", [str characterAtIndex:i]];
[letters addObject:letter];
}
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
NSLog(#"Value is : %i", value);
[letters exchangeObjectAtIndex:i withObjectAtIndex:value];
}
NSString *results = [letters componentsJoinedByString:#""];
NSLog(#"The string before : %#", str);
NSLog(#"This is the string now : %#", results);

Cant replace string in NSMutableString

This is my string:
2011-10-07T08:55:16-05:00
I am trying to remove the colon with this code:
NSRange range = NSMakeRange(dateString.length-3, 1);
NSString *temp = [dateString substringWithRange:range];
if ([temp isEqualToString:#":"])
[dateString replaceCharactersInRange:range withString:#""];
My code enters the if statement, so I know that it found the colon. But it crashes with no errors on the last line. What am I doing wrong?
try this :
NSMutableString *dateString = [NSMutableString stringWithString:#"2011-10-07T08:55:16-05:00"];
NSRange range = NSMakeRange(dateString.length-3, 1);
NSString *temp = [dateString substringWithRange:range];
if ([temp isEqualToString:#":"])
[dateString replaceCharactersInRange:range withString:#""];

nsstring replace string in range

I have a string with certain pattern. I need to search for the pattern and replace the string inside that pattern. For eg :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSString *result = nil;
// Determine "{" location
NSRange startRange = [string rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [string length] - endRange.location;
endRange = [string rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
result = [string substringWithRange:startRange];
}
}
Here I am able to extract the first substring that is between "{ }" ie - "Hello" but I also need to continue the check and want to extract other strings.
Try this one:
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
//NSString *result = nil;
// Determine "{" location
NSArray *array=[string componentsSeparatedByString:#"{"];
for(NSString *str in array){
NSString *newString=[[str componentsSeparatedByString:#"}"] objectAtIndex:0];
NSLog(#"%#",newString);
}
try this :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSMutableString *result = [[NSMutableString alloc] init];
NSArray *tempArray = [[string componentsSeparatedByString:#" "] mutableCopy];
for (int i=0; i < [tempArray count]; i++)
{
NSString *tempStr = [tempArray objectAtIndex:i];
NSRange startRange = [tempStr rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [tempStr length] - endRange.location;
endRange = [tempStr rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
//result = [tempStr substringWithRange:startRange];
[result appendString:[NSString stringWithFormat:#"%# ",[tempStr substringWithRange:startRange]]];
NSLog(#"%# ",result);
}
}
}
Take care for release for tempArray and result
I happen to have this code lying around. I think it does exactly what you want. I implemented it as a category on NSString. You use it like this:
NSString *template = #"{Hello} ({World}) ({How}) etc etc";
NSDictionary *vars = [NSDictionary dictionaryWithObjectsAndKeys:
#"Bonjour", #"Hello",
#"Planet Earth", #"World",
#"Como", #"How",
// etc.
nil];
NSString *expandedString = [template stringByExpandingTemplateWithVariables:vars];
// expandedString is #"Bonjour (Planet Earth) (Como) etc etc"
Here's the code.
File NSString+TemplateExpansion.h
#import <Foundation/Foundation.h>
#interface NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary;
#end
File NSString+TemplateExpansion.m
#import "NSString+TemplateExpansion.h"
#implementation NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary
{
NSUInteger myLength = self.length;
NSMutableString *result = [NSMutableString stringWithCapacity:myLength];
NSRange remainingRange = NSMakeRange(0, myLength);
while (remainingRange.length > 0) {
NSRange leftBraceRange = [self rangeOfString:#"{" options:0 range:remainingRange];
if (leftBraceRange.location == NSNotFound)
break;
NSRange afterLeftBraceRange = NSMakeRange(NSMaxRange(leftBraceRange), myLength - NSMaxRange(leftBraceRange));
NSRange rightBraceRange = [self rangeOfString:#"}" options:0 range:afterLeftBraceRange];
if (rightBraceRange.location == NSNotFound)
break;
NSRange beforeLeftBraceRange = NSMakeRange(remainingRange.location, leftBraceRange.location - remainingRange.location);
[result appendString:[self substringWithRange:beforeLeftBraceRange]];
remainingRange = NSMakeRange(NSMaxRange(rightBraceRange), myLength - NSMaxRange(rightBraceRange));
NSRange keyRange = NSMakeRange(NSMaxRange(leftBraceRange), rightBraceRange.location - NSMaxRange(leftBraceRange));
NSString *key = [self substringWithRange:keyRange];
NSString *value = [dictionary objectForKey:key];
if (value)
[result appendString:value];
}
[result appendString:[self substringWithRange:remainingRange]];
return result;
}
#end

iphone sdk - Remove all numbers except for characters a-z from a string

In my app I want to remove numbers except characters a-z from string. How can I get only characters?
This is the short answer which doesnt need any lengthy coding
NSString *newString = [[tempstr componentsSeparatedByCharactersInSet:
[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:#""];`
swift 3:
(tempstr.components(separatedBy:NSCharacterSet.letters.inverted)).joined(separator: "")
eg:
("abc123".components(separatedBy:NSCharacterSet.letters.inverted)).joined(separator: "")
NSString *stringToFilter = #"filter-me";
NSMutableString *targetString = [NSMutableString string];
//set of characters which are required in the string......
NSCharacterSet *okCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyz"];
for(int i = 0; i < [stringToFilter length]; i++)
{
unichar currentChar = [stringToFilter characterAtIndex:i];
if([okCharacterSet characterIsMember:currentChar])
{
[targetString appendFormat:#"%C", currentChar];
}
}
NSLog(targetString);
[super viewDidLoad];
}
this was an answer given to me and works fine
I found an answer:
from remove-all-but-numbers-from-nsstring
NSString *originalString = #"(123) 123123 abc";
NSLog(#"%#", originalString);
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyz"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSLog(#"%#", strippedString);

Subtracting 2 strings

I have a string say for example #"012" and I have another string #"02". How can I extract the difference of the 2 strings in iPhone Objective-C. I just need to remove the existence of the characters in the 2nd string from the first string.The answer would be "1".
Even shorter:
NSString* s1 = #"012";
NSString* s2 = #"02";
NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:s2];
NSString * final = [[s1 componentsSeparatedByCharactersInSet:set] componentsJoinedByString:#""];
NSLog(#"Final: %#", final);
This preserves the order of the characters in the original string.
You could do something like this;
NSString *s1 = #"012";
NSString *s2 = #"02";
NSCharacterSet *charactersToRemove;
charactersToRemove = [NSCharacterSet characterSetWithCharactersInString:s2];
NSMutableString *result = [NSMutableString stringWithCapacity:[s1 length]];
for (NSUInteger i = 0; i < [s1 length]; i++) {
unichar c = [s1 characterAtIndex:i];
if (![charactersToRemove characterIsMember:c]) {
[result appendFormat:#"%C", c];
}
}
// if memory is an issue:
result = [[result copy] autorelease];
Disclaimer: I typed this into the browser, and haven't tested any of this.
You're trying to do a set operation, so use sets.
{
NSString* s1 = #"012";
NSString* s2 = #"02";
NSMutableSet* set1 = [NSMutableSet set];
NSMutableSet* set2 = [NSMutableSet set];
for(NSUInteger i = 0; i < [s1 length]; ++i)
{
[set1 addObject:[s1 substringWithRange:NSMakeRange(i, 1)]];
}
for(NSUInteger i = 0; i < [s2 length]; ++i)
{
[set2 addObject:[s2 substringWithRange:NSMakeRange(i, 1)]];
}
[set1 minusSet:set2];
NSLog(#"set1: %#", set1);
// To get a single NSString back from the set:
NSMutableString* result = [NSMutableString string];
for(NSString* piece in set1)
{
[result appendString:piece];
}
NSLog(#"result: %#", result);
}
I simply used "componentsSeparatedByString"
NSString *s1 = #"abc";
NSString *s2 = #"abcdef";
//s2 - s1
NSString * final = [[s2 componentsSeparatedByString:s1] componentsJoinedByString:#""];