How can I extract the first 3 characters from an NSString? [duplicate] - ios

This question already has answers here:
how to get first three characters of an NSString?
(3 answers)
Closed 6 years ago.
How can I extract the first 3 characters from a NSString?
For example if I have a string "1234820" How can I extract the numbers 123 from the string and store the result in a new string with the format "1.23 Million" ?
I am counting the the number of characters in the string by using
-(NSString *)returnFormattedString:(NSString *)stringToFormat{
NSString *formatedString;
NSUInteger characterCount = [stringToFormat length];
if (characterCount > 6) {
//???? How do I extract and add a decimal
stringWithThreeCharactersAndDecimal = ????;
NSString *string = [NSString stringWithString:stringWithThreeCharactersAndDecimal];
formatedString = [string stringByAppendingString:#"Million"];
}
return formatedString;
}

do like
assume that is your String
yourString = #"1234820";
// use substringToIndex for fetch First Three Character
yourString=[yourString substringToIndex:3];
// finally convert string to as like 1.23
NSString *finalStr = [NSString stringWithFormat:#"%.2f Million", [yourString floatValue]];
Choice -2
as per Droppys short and good answer is
NSString *finalStr = [NSString stringWithFormat:#"%.2f Million", [yourString floatValue] / 100.0f];

Related

Extract integer from a string in objective c [duplicate]

This question already has answers here:
Objective-C: Find numbers in string
(7 answers)
Closed 7 years ago.
i have a string which has both numeric and character value.
Like: string = abc1234
Now I want to get only the integer part from it:
i.e. 1234
How can I do this? I have tried the following with no luck:
NSString *str = #"abc123";
int s = [str intValue];
Use this function
- (NSString *)extractNumberFromText:(NSString *)text
{
NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return [[text componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:#""];
}
It will help you.Thankyou

How to get particular string from my response? [duplicate]

This question already has answers here:
Objective-C Split()?
(5 answers)
Closed 8 years ago.
I have received below string response
USA : United states of america
i need to get before ":" data's. Below I have posted sample what i need?
USA
Hi i think you need to check if the ":" char is exists first because it will crash.
here is example for how to do it:
NSString *yourString = #"USA : bla bla bal";
NSRange range = [yourString rangeOfString:#":"];
if(range.location != NSNotFound) // string contains
{
int indexOf = range.location;
NSString *prefix = [yourString substringWithRange:NSMakeRange(0, indexOf)];
// prefix = "USA "
}
if you want you can trim the prefix string and remove all the empty spaces like this
NSString *trimmedString = [prefix stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
Try like this:-
NSString*yourStr=#"USA : United states of america";
NSString *str=[yourStr componentsSeparatedByString:#":"][0];
NSLog(#"%#",str);

How to not show unnecessary zeros when given integers but still have float answers when needed

I have an app I'm developing and one of my features is giving answers in float or double values when needed and an integer when the answer is a whole number
so for example if the answer comes out to 8.52 the answer becomes 8.52 but when the answer is 8 the answer is 8 instead of 8.0000, i don't want it to show all the extra 0s.
- (IBAction) equalsbutton {
NSString *val = display.text;
switch(operation) {
case Plus :
display.text= [NSString stringWithFormat:#"%qi",[val longLongValue]+[storage longLongValue]];
case Plus2 :
display.text= [NSString stringWithFormat:#"%f",[val doubleValue]+[storage doubleValue]];
this code doesn't seem to work
These specifiers are standard IEEE format specifiers, which means that you can do things like %.2f to only show 2 decimal places on a float variable.
You could also convert it into an int, and then use the %d format specifier if you wanted to do it that way.
Here's also Apple's documentation on the subject.
EDIT: Based on your comment on the other post, it looks like you're looking for %g, which will essentially remove the extraneous 0's from floats.
display.text= [NSString stringWithFormat:#"%g",[val doubleValue]+[storage doubleValue]];
I found the answer here: Use printf to format floats without decimal places if only trailing 0s
EDIT Formatting
Here is a way that I did this when I needed to display currency (but whole numbers if the currency was a round number.
First we get the money amount as a string
NSString *earnString = _money.payout.displayableAmount;
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:earnString.length];
//scan the string to remove anything but the numbers (including decimals points)
NSScanner *scanner = [NSScanner scannerWithString:earnString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
//create an int with this new string
int earnInt = [strippedString intValue];
//if the string is less than 100 then we only had "change" so display that amount
if(earnInt < 100){
//Dollar amount is less then dollar display just the cents and the cent symbol
NSString *centString = [NSString stringWithFormat:#"%i¢", earnInt];
earnAmount.text = centString;
//if we have a number evenly divisible by 100 then we have whole dollar amount, display that properly
}else if(earnInt % 100 == 0){
//The amount is exactly a dollar, display the whole number
NSString *wholeDollar = [NSString stringWithFormat:#"$%i", (earnInt/100)];
earnAmount.text = wholeDollar;
//finally if we have a mixed number then put them back together with the decimal in-between.
}else{
//Dollar amount is not exactly a dollar display the entire amount
NSString *dollarString = [NSString stringWithFormat: #"$%0d.%02d", (earnInt / 100), (earnInt % 100)];
earnAmount.text = dollarString;
}
Hopefully this helps you out...
You can try this method call:
[NSString stringWithFormat:#"%.0f", [val doubleValue] + [storage doubleValue]];
Easiest way, is NSNumberFormatter. It will only display the decimal if needed. Example (Swift):
let num1: Double = 5
let num2: Double = 5.52
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .DecimalStyle
print(numberFormatter.stringFromNumber(NSNumber(double: num1)))
print(numberFormatter.stringFromNumber(NSNumber(double: num2)))
This will print 5 and then 5.52.

componentsSeperatedByString returns full word [duplicate]

This question already has answers here:
Is there a simple way to split a NSString into an array of characters?
(4 answers)
Closed 9 years ago.
I am trying to get each letter of an NSString using this line of code:
NSArray *array = [string componentsSeparatedByString:#""];
//string is equal to Jake
NSLog(#"Array Count:%d",[array count]);
I am expecting to get each letter of the word "Jake" but instead I am getting the whole word. Why?
From Apple's Doc about this method
NSString *list = #"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:#", "];
produces an array { #"Norman", #"Stanley", #"Fletcher" }.
So empty separator will not separate each character of string, this
method doesn't work this way.
Here is an answer for your question
How to convert NSString to NSArray with characters one by one in Objective-C
The idea of separating a string by nothing doesn't logically make sense, it is like trying to divide by zero.
But to answer the question:
NSMutableArray *stringComponents = [NSMutableArray arrayWithCapacity:[string length]];
for (int i = 0; i < [string length]; i++) {
NSString *character = [NSString stringWithFormat:#"%c", [string characterAtIndex:i]];
[stringComponents addObject:character];
}`

Extracting from the right of a string in objective C [duplicate]

This question already has answers here:
Get last 2 characters of a string?
(2 answers)
Closed 9 years ago.
This seems to be what I'm looking for but in reverse. I would like the string to extract from the right not from the left.
The example extracting from the left is given:
NSString *source = #"0123456789";
NSString *firstFour = [source substringToIndex:4];
Output: "0123"
I'm looking for a version of the below that works from the right (what is below doesn't work)
NSString *source = #"0123456789";
NSString *lastFour = [source substringToIndex:-4];
Output: "6789"
the [source substringFromIndex:6]; won't work because sometimes I will get an answer that is 000123456789 or 456789 or 6789. In all cases I just need the last 4 characters from the string so that I can convert it to a number.
there must be a better way than a bunch of if else statements?
As you are not sure, about the length of the string, so you must check it before extracting like this:
NSString *source = #"0123456789";
NSNumber *number;
if (source.length>=4) {
NSString *lastFour=[source substringFromIndex:source.length-4];
number=#([lastFour integerValue]); //and save it in a number, it can be int or NSInteger as per your need
}
NSLog(#"%#",number);
Also if you want a quick method that you need to call several times, create a category :
#implementation NSString (SubstringFromRight)
-(NSString *)substringFromRight:(NSUInteger)from{
if (self.length<from) {
return nil;
}
return [self substringFromIndex:self.length-from];
}
#end
And use it as :NSLog(#"%#",[source1 substringFromRight:4]);
NSString *source = #"0123456789";
NSString *newString = [source substringFromIndex:[source length] - 4];
NSLog(#"%#",newString);
replace
NSString *lastFour = [source substringToIndex:-4];
with
NSString *lastFour = [source substringFromIndex:[source length] - 4];
which returns you the last 4 characters of your original string string in lastFour string.
You can use the following code to get last 4 characters from your string.
NSString *last4Characters = [source substringFromIndex:(source.length - 4)];
NSLog(#"Last 4 Characters:%#",last4Characters);
last4Characters=nil;
Please let me know if any issue.

Resources