Getting more than char from string variable - ios

I have an NSString *fileName
This will contain a variable number from 1 to 3 digits. I want to extract all of the digits
I can get the first digit using
//create text for appliance identifier
char obsNumber = [fileName characterAtIndex:3];//get 4 character
NSLog(#"Obs number %c",obsNumber);
//Text label
[cell.titleLabel setText:[NSString stringWithFormat:#"Item No: %c",obsNumber]];
NSLog(#"Label for observation = %#",cell.titleLabel.text);
However if the string contains the number for example 78, or 204 I want to catch all two or three digits.
I tried this
//create text for appliance identifier
char obsNumber1 = [fileName characterAtIndex:3];//get 4 character
char obsNumber2 = [fileName characterAtIndex:4];//get 5 character
char obsNumber3 = [fileName characterAtIndex:5];//get 6 character
NSLog(#"Obs number %c,%c,%c",obsNumber1,obsNumber2,obsNumber3);
//Text label
[cell.titleLabel setText:[NSString stringWithFormat:#"Item No: %c,%c,%c",obsNumber1,obsNumber2,obsNumber3]];
NSLog(#"Label for observation = %#",cell.titleLabel.text);
This gave me 18c 1ce etc

Would this work for you?
NSString *filename = #"obs127observation"; //An example variable with your format
This code could be tidier but you should get the idea:
NSString *filenameNumber = [[filename
stringByReplacingOccurrencesOfString:#"observation"
withString:#""]
stringByReplacingOccurrencesOfString:#"obs"
withString:#""];

you can trim other letters except the decimals.
NSString *onlyNumbers=[yourstring stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];

As your comment says , It has predefined set of values, right. Then try like this
NSstring *str = [filename substringFromIndex:11];
// Convert the str to char[]
Then you should try with the NSScanner :
NSString *numberString;
NSScanner *scanner = [NSScanner scannerWithString:filename];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
// Throw away characters before the first number.
[scanner scanUpToCharactersFromSet:numbers intoString:NULL];
// Collect numbers.
[scanner scanCharactersFromSet:numbers intoString:&numberString];
// Result.
int number = [numberString integerValue];
// you can play around with the set of number

Your approach of separating one character at a time and then combining them back into a string is an awkward, overly complex way of going about this. Kumar's suggestion of using NSScanner is a good option if you have a number in the middle of a string.
However, you make it sound like your string will always contain a number and only a number. Is that true? Or will there be characters you need to ignore?
You need to define the problem clearly and completely before you can select the best solution.
It might be as simple as using the NSString method substringWithRange.

Related

NSString stringWithCString not showing special characters?

I'm using
[NSString stringWithFormat:#"%C",(unichar)decimalValueX];
but I have to call it thousands of times and its simply too slow.
As an alternative I tried this:
sprintf (cString, "%C", (unichar)decimalValueX);
[NSString stringWithCString:cString encoding:NSUTF16StringEncoding];
but no characters are correctly transalted.
If I try UTF8 instead of 16:
sprintf (cString, "%C", (unichar)decimalValueX);
[NSString stringWithCString:cString encoding:NSUTF8StringEncoding];
I get alphanumeric, but I don't get foreign characters or other special characters.
Can anyone explain whats going on? Or how to make stringWithFormat faster?
Thanks!
It seems that the %C format does not work with sprintf and related functions and non-ASCII characters. But there is a simpler method:
stringWithCharacters:length:
creates an NSString directly from a unichar array (UTF-16 code points).
For a single unichar this would be just
NSString *string = [NSString stringWithCharacters:&decimalValueX length:1];
Example:
unichar decimalValueX = 8364; // The Euro character
NSString *string = [NSString stringWithCharacters:&decimalValueX length:1];
NSLog(#"%#", string); // €
Example for multiple UTF-16 code points:
unichar utf16[] = { 945, 946, 947 };
NSString *string3 = [NSString stringWithCharacters:utf16 length:3];
NSLog(#"%#", string3); // αβγ
For characters outside of the "basic multilingual plane" (i.e.
characters > U+FFFF) you would have to use 2 UTF-16 code points
per character (surrogate pair).
Or use a different API like
uint32_t utf32[] = { 128123, 128121 };
NSString *string4 = [[NSString alloc] initWithBytes:utf32 length:2*4 encoding:NSUTF32LittleEndianStringEncoding];
NSLog(#"%#", string4); // 👻👹

How to remove white space from Phone Number in iOS [duplicate]

This question already has answers here:
How to remove non numeric characters from phone number in objective-c?
(5 answers)
Closed 6 years ago.
I can't remove white space from Phone Number in iOS app.
Here is my codes.
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for (CFIndex iPhone = 0; iPhone < ABMultiValueGetCount(multiPhones); iPhone++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, iPhone);
NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;
if (phoneNumber == nil) {
phoneNumber = #"";
}
if (phoneNumber.length == 0) continue;
// phone number = (217) 934-3234
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
// phone number = 217 9343234
[phoneNumbers addObject:phoneNumber];
}
I expect to get without white space. But it is not removed from the phone number.
How can I fix? Please help me. Thanks
You can do something a lot simpler than what you're currently doing with NSCharacterSet. Here's how:
NSCharacterSet defines a collection of characters. There are a few standard ones, such as decimalDigitsCharacterSet and alphaNumericCharacterSet.
There's also a neat method called invertedSet which returns a character set with all of the characters not included in the current one. Now, we need just one more bit of information.
NSString has a method called componentsSeparatedByCharactersInSet:, which gives you back an NSArray of the parts of the string, broken up around the characters in the characterSet you supply.
NSArray has a complementary function, componentsJoinedWithString: which you can use to turn the elements of an array (back) into a string. See where this is going?
First, define a character set that we want to include in our final output:
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
Now, get everything else.
NSCharacterSet *illegalCharacters = [digits invertedSet]
Once we have the character set that we want, we can break out the string and reconstruct it:
NSArray *components = [phoneNumber componentsSeperatedByCharactersInSet:illegalCharacters];
NSString *output = [components componentsJoinedByString:#""];
That should give you the correct output. Four lines, and you're done:
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *illegalCharacters = [digits invertedSet];
NSArray *components = [phoneNumber componentsSeparatedByCharactersInSet:illegalCharacters];
NSString *output = [components componentsJoinedByString:#""];
You can use the whitespaceCharacterSet do do something similar to trim whitespace off of strings.
NSHipster has a great article about this, too.
EDIT:
If you want to include other symbols, such as the + prefix or parenthesis, you can create custom character sets with characterSetWithCharactersInString:. If you have two character sets, such as the decimal digits and the custom one you created, you could use NSMutableCharacterSet to modify the character set you have to include other characters.

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

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);

Extract number(amount of money) from a sentence in iOS

I need to extract out the amount from the sentences containing amount information like "Rs 500".
E.g => "Product costs Rs 500, would you like to buy???",
I need the solution in regex, please share the code using NSRegularExpression class to extract amount from the sentence, "Rs" must be case-insensitive.
I am weak in writing regex, hence need the same.
If you are not efficient in using Regular Expression. You can use NSScanner to get the number as below
// Input
NSString *originalString = #"Product costs Rs 500, would you like to buy???";
// Intermediate
NSString *numberString;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
// Throw away characters before the first number.
[scanner scanUpToCharactersFromSet:numbers intoString:NULL];
// Collect numbers.
[scanner scanCharactersFromSet:numbers intoString:&numberString];
// Result.
int number = [numberString integerValue];
Hope it Helps you...

Get the unique characters in an NSString

How can I get the unique characters in an NSString?
What I'm trying to do is get all the illegal characters in an NSString so that I can prompt the user which ones were inputted and therefore need to be removed. I start off by defining an NSCharacterSet of legal characters, separate them with every occurrence of a legal character, and join what's left (only illegal ones) into a new NSString. I'm now planning to get the unique characters of the new NSString (as an array, hopefully), but I couldn't find a reference anywhere.
NSCharacterSet *legalCharacterSet = [NSCharacterSet
characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789-()&+:;,'.# "];
NSString *illegalCharactersInTitle = [[self.titleTextField.text.noWhitespace
componentsSeparatedByCharactersInSet:legalCharacterSet]
componentsJoinedByString:#""];
That should help you. I couldn't find any ready to use function for that.
NSMutableSet *uniqueCharacters = [NSMutableSet set];
NSMutableString *uniqueString = [NSMutableString string];
[illegalCharactersInTitle enumerateSubstringsInRange:NSMakeRange(0, illegalCharactersInTitle.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if (![uniqueCharacters containsObject:substring]) {
[uniqueCharacters addObject:substring];
[uniqueString appendString:substring];
}
}];
Try with the following adaptation of your code:
// legal set
NSCharacterSet *legalCharacterSet = [NSCharacterSet
characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789-()&+:;,'.# "];
// test strings
NSString *myString = #"LegalStrin()";
//NSString *myString = #"francesco#gmail.com"; illegal string
NSMutableCharacterSet *stringSet = [NSCharacterSet characterSetWithCharactersInString:myString];
// inverts the set
NSCharacterSet *illegalCharacterSet = [legalCharacterSet invertedSet];
// intersection of the string set and the illegal set that modifies the mutable stringset itself
[stringSet formIntersectionWithCharacterSet:illegalCharacterSet];
// prints out the illegal characters with the convenience method
NSLog(#"IllegalStringSet: %#", [self stringForCharacterSet:stringSet]);
I adapted the method to print from another stackoverflow question:
- (NSString*)stringForCharacterSet:(NSCharacterSet*)characterSet
{
NSMutableString *toReturn = [#"" mutableCopy];
unichar unicharBuffer[20];
int index = 0;
for (unichar uc = 0; uc < (0xFFFF); uc ++)
{
if ([characterSet characterIsMember:uc])
{
unicharBuffer[index] = uc;
index ++;
if (index == 20)
{
NSString * characters = [NSString stringWithCharacters:unicharBuffer length:index];
[toReturn appendString:characters];
index = 0;
}
}
}
if (index != 0)
{
NSString * characters = [NSString stringWithCharacters:unicharBuffer length:index];
[toReturn appendString:characters];
}
return toReturn;
}
First of all, you have to be careful about what you consider characters. The API of NSString uses the word characters when talking about what Unicode refers to as UTF-16 code units, but dealing with code units in isolation will not give you what users think of as characters. For example, there are combining characters that compose with the previous character to produce a different glyph. Also, there are surrogate pairs, which only make sense when, um, paired.
As a result, you will actually need to collect substrings which contain what the user thinks of as characters.
I was about to write code very similar to Grzegorz Krukowski's answer. He beat me to it, so I won't but I will add that your code to filter out the legal characters is broken because of the reasons I cite above. For example, if the text contains "é" and it's decomposed as "e" plus a combining acute accent, your code will strip the "e", leaving a dangling combining acute accent. I believe your intent is to treat the "é" as illegal.

Resources