How do I easily strip just a comma from an NSString? - ios

I have a UILabel with the following text:
Medium, Black
What I intended to do was grab the words in the string and insert each into a mutable array so I could use each title later on to identify something.
Here's how I done this:
NSMutableArray *chosenOptions = [[[[cell tapToEditLabel] text] componentsSeparatedByString: #" "] mutableCopy];
NSString *size = [chosenOptions objectAtIndex:0];
NSString *colour = [chosenOptions objectAtIndex:1];
I've logged these two NSString and size is returning "Medium," and colour is correctly returning "Black".
My comparison result is always false because of the comma:
itemExists = [[item colour] isEqualToString:colour] && [[item size] isEqualToString:size] ? YES : NO;
That comma causes itemExists to always equal NO.
Would appreciate a simple solution in code please.
The solution needs to only strip commas and not other characters. When dealing with clothing sizes for females I use sizes in a string like this: "[8 UK]" so remove non-alphanumeric characters would remove these. So I really need a solution to deal with just the commas.
Thanks for your time.

Rather than splitting on spaces, you could split on spaces or commas, like this:
NSMutableArray *chosenOptions = [[[[cell tapToEditLabel] text] componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#" ,"]] mutableCopy];
[chosenOptions removeObject:#""];
This would eliminate commas from the size and colour strings.

[yourString stringByReplacingOccurrencesOfString:#"," withString:#""];
easy squeezy lemon peesey

Try this:
NSString * myString = #"Medium, Black";
NSString * newString = [myString stringByReplacingOccurrencesOfString:#", " withString:#""];
NSLog(#"%#xx",newString);

Related

Using componentsSeparatedByString with more than one separator string?

I have a string that I need to separate into an array of words. I was using NSArray *words = [cleanText componentsSeparatedByString:#" "]; which worked fine, until I ran into the end of a paragraph resulting in the component "end.\n\nStart".
Is there a way to separate the string into components using " " as well as "\n\n" character? Or is there more correct way to solve this?
You are describing splitting a string using a regular expression such as "\s". If you look at e.g. https://github.com/bendytree/Objective-C-RegEx-Categories/blob/master/RegExCategories.m you can obtain code for splitting on a regular expression match.
Alternatively you can split on a character set by calling componentsSeparatedByCharactersInSet: and use whitespaceAndNewlineCharacterSet.
You can split on the whitespaceAndNewlineCharacterSet. You will get empty “words” when cleanText has more than one split character in a row, and you probably want to filter those out.
NSArray *words = [#"" componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
words = [words filteredArrayUsingPredicate:
[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *_) {
return [object length] > 0;
}]];

Removing Specific Characters from NSString

For example if i had a string like
NSString *myString = #"A B C D E F G";
and I want to remove the spaces, and get a string out like "ABCDEFG".
I could use
NSString *stringWithoutSpaces = [myString stringByReplacingOccurrencesOfString:#" " withString:#""];
However, for my application I am loading in phone numbers from the address book
and the numbers often have a different formatting layout.
I'm wondering if I have a phone number stored in a string like
+1-(937)673-3451 how would I go about removing only the first "1" the "+" the "-" and the "(" ")".
Overall, I would like to know if it is possible to remove the first "1" without removing the last one in the string?
There are a lot of ways to do this. Here's one:
NSString *phoneNumber = #"+1-(937)673-3451";
NSCharacterSet *removalCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"+()-"];
NSArray *components = [phoneNumber componentsSeparatedByCharactersInSet:removalCharacterSet];
NSString *simplifiedPhoneNumber = [components componentsJoinedByString:#""];
NSRange firstCharacterRange = NSMakeRange(0, 1);
if ([[simplifiedPhoneNumber substringWithRange:firstCharacterRange] isEqualToString:#"1"]) {
simplifiedPhoneNumber = [simplifiedPhoneNumber stringByReplacingCharactersInRange:firstCharacterRange withString:#""];
}
NSLog(#"Full phone number: %#", phoneNumber);
NSLog(#"Simplified phone number: %#", simplifiedPhoneNumber);
But really you want to use a library that knows what a phone number is supposed to look like, like libPhoneNumber.

seperation of strings with special characters

I am making a calculator and unable to seperate the input string in corrosponding to operands.
For example : 2*5 - 6 +8/2. I want an array with components 2, 5, 6, 8, 2 so that I can store the oprators also and then sort accordingly. Please help
NSString *str=#"2*5 - 6 +8/2"; // assume that this is your str
// here remove the white space
str =[str stringByReplacingOccurrencesOfString:#" " withString:#""];
// here remove the all special characters in NSString
NSCharacterSet *noneedstr = [NSCharacterSet characterSetWithCharactersInString:#"*/-+."];
str = [[str componentsSeparatedByCharactersInSet: noneedstr] componentsJoinedByString:#","];
NSLog(#"the str=-=%#",str);
the out put is
the str=-=2,5,6,8,2
You can use the method, componentsSeparatedByCharactersInSet:.
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"*-+/"];
NSArray *numbers = [text componentsSeparatedByCharactersInSet:set];
You can get arrays of the operands and operators like so. This assumes the expression is valid, base 10, begins and ends with operands, etc. The expression would then be operands[0], operators[0], operands[1], operators[1], and so on.
NSString *expression = #"2*5 - 6 +8/2";
// Could use a custom character set as well, or -whitespaceAndNewlineCharacterSet
NSCharacterSet *whitespaceCharacterSet = [NSCharacterSet whitespaceCharacterSet];
NSArray *nonWhitespaceComponents = [expression componentsSeparatedByCharactersInSet:whitespaceCharacterSet];
NSString *trimmedExpression = [nonWhitespaceComponents componentsJoinedByString:#""];
// To get an array of the operands:
NSCharacterSet *operatorCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"+-/*"];
NSArray *operands = [trimmedExpression componentsSeparatedByCharactersInSet:operatorCharacterSet];
// To get the array of operators:
NSCharacterSet *baseTenCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
NSArray *operators = [trimmedExpression componentsSeparatedByCharactersInSet:baseTenCharacterSet];
// Since expression should begin and end with operands, first and last strings will be empty
NSMutableArray *mutableOperators = [operators mutableCopy];
[mutableOperators removeObject:#""];
operators = [NSArray arrayWithArray:mutableOperators];
NSLog(#"%#", operands);
NSLog(#"%#", operators);

Cut NSString from space to end

I have NSString:
sessid=os3vainreuru2hank3; __ubic1=MzcxMzjMDYuNjk0NDA1Mzc%3D;
auto_login=123; sid=kep8efpo7; last_user=123;
I need get just:
__ubic1=MzcxMzjMDYuNjk0NDA1Mzc%3D; auto_login=123;
interpals_sessid=kep8efpo7; last_user=123;
But count of characters past sessid may vary
Thanks! Sorry for simple question
This should do the trick.-
NSRange range = [yourString rangeOfString:#" "];
if (NSNotFound != range.location) {
yourString = [yourString substringFromIndex:(range.location + 1)];
}
Basically, you get the index for the first space character, and then the substring from that index to the end.
You'll need at least one character you can search for. Looks like that double underscore will work.
NSRange stringStart = [originalString rangeOfString:#"__"];
NSString *extractedString = [originalString substringWithRange:NSMakeRange(stringStart.location, originalString.length - stringStart.location)];
That should get you what you need!
NSMutableArray* array = [[originalString componentsSeperatedByString:#";"] mutableCopy];
[array removeObjectAtIndex:0];
NSString* newString = [array componentsJoinedByString:#";"];
I assume you mistyped interpals_sessid with sid

How to find the next line in the nsstring

Is there any way to find the next line characters in the nsstring. I mean second line of characters...
I want to find the word in the second line of nsstring... Plz help me out guys...Am newbie to xcode...
Am using
NSString *substring = [text substringToIndex:[text rangeOfString:#" "].location];
i want to find out that empty space in the entire text... I'm able to find that empty space in the first line of nsstring.. But in the second line also having same empty space.. but it is not recognising...
You can split on \n character.
Something like this:
NSArray *vals = [yourString componentsSeparatedByString:#"\n"];
Then check if vals has more than one element.
if ([vals count] > 1) {
// you do have a "next line"
NSString *nextLine = [vals objectAtIndex: 1];
NSLog(nextLine);
}
NSArray *lines = [yourNSStringObject componentsSeparatedByString:#"\n"];
NSString *secondline = [lines objectAtIndex:1];
There's an overload method for rangeOfString that you can provide a range for it.
Try this:
NSString *substring = [text substringToIndex:[text rangeOfString:#" " options:nil range:NSMakeRange([text rangeOfString:#"\n"], text.length)].location];

Resources