How to get the string value from a string which contains ","? - iphone

I have a string value where it contains comma. Ex:- 1,234. I want to get the value of the string where i need only 1234. Can you please help me...

Instead of manually stripping out the commas, it might be more elegant (and less error-prone if you support different locales) to use an NSNumberFormatter to convert the string to a number.

NSString *myString = "1,234";
NSString *resultString = [myString stringByReplacingOccurrencesOfString:#"," withString:#""];

If you want to strip the comma then: -
NSString *string = #"1,234";
string = [string stringByReplacingOccurrencesOfString:#"," withString:#""];
This should return you a string with just 1234 in it.
By 'getting the value' do you mean, converting this to a NSNumber object? If so use this
NSNumber *numberFromString = [NSNumber numberWithInteger:[string integerValue]];

I don't know that framework/language, but if an integer converter won't work, then strip out the commas by replacing them with null from the string and then convert to an integer.

Related

Convert or Print CGPDFStringRef string

How to convert a CGPDFStringRef to unicode char? I have used CGPDFStringCopyTextString to get the string and then [string characterAtIndex:i] to cast to unichar, is this the right way? or is there any way to get the bytes of the string and convert to unicode directly?
Need some guidance here.
NSString is capable of handling of unicode characters itself, you just need to convert the CGPDFString to NSString and further you can use it as follows:
NSString *tempStr = (NSString *)CGPDFStringCopyTextString(objectString);
although UPT's answer is correct, it will produce a memory leak
from the documentation:
CGPDFStringCopyTextString
"...You are responsible for releasing this object."
the correct way to do this would be:
CFStringRef _res = CGPDFStringCopyTextString(pdfString);
NSString *result = [NSString stringWithString:(__bridge NSString *)_res];
CFRelease(_res);
It's not a bad idea, even if you can access the CGPDFString directly using CGPDFStringGetBytePtr. You will also need CGPDFStringGetLength to get the string length, as it may not be null-terminated.
See the documentation for more info

How can I remove quotes from an NSString?

I am trying to remove quotes from something like:
"Hello"
so that the string is just:
Hello
Check out Apple's docs:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/
You probably want:
stringByReplacingOccurrencesOfString:withString:
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
So, something like this should work:
newString = [myString stringByReplacingOccurrencesOfString:#"\"" withString:#""];
I only wanted to remove the first quote and the last quote, not the quotes within the string so here's what I did:
challengeKey = #"\"I want to \"remove\" the quotes.\"";
challengeKey = [challengeKey substringFromIndex:1];
challengeKey = [challengeKey substringToIndex:[challengeKey length] - 1];
Hope this helps others looking for the same thing. NSLog and you'll get this output:
I want to "remove" the quotes.

ObjectiveC Parse Integer from String

I'm trying to extract a string (which contains an integer) from an array and then use it as an int in a function. I'm trying to convert it to a int using intValue.
Here's the code I've been trying.
NSArray *_returnedArguments = [serverOutput componentsSeparatedByString:#":"];
[_appDelegate loggedIn:usernameField.text:passwordField.text:(int)[[_returnedArguments objectAtIndex:2] intValue]];
I get this error:
passing argument 3 of 'loggedIn:::' makes pointer from integer
without a cast
What's wrong?
I really don't know what was so hard about this question, but I managed to do it this way:
[myStringContainingInt intValue];
It should be noted that you can also do:
myStringContainingInt.intValue;
You can just convert the string like that [str intValue] or [str integerValue]
integerValue
Returns the NSInteger value of the receiver’s text.
(NSInteger)integerValue
Return Value
The NSInteger value of the receiver’s text, assuming a decimal representation and skipping whitespace at the beginning of the string. Returns 0 if the receiver doesn’t begin with a valid decimal text representation of a number.
for more information refer here
NSArray *_returnedArguments = [serverOutput componentsSeparatedByString:#":"];
_returnedArguments is an array of NSStrings which the UITextField text property is expecting. No need to convert.
Syntax error:
[_appDelegate loggedIn:usernameField.text:passwordField.text:(int)[[_returnedArguments objectAtIndex:2] intValue]];
If your _appDelegate has a passwordField property, then you can set the text using the following
[[_appDelegate passwordField] setText:[_returnedArguments objectAtIndex:2]];
Basically, the third parameter in loggedIn should not be an integer, it should be an object of some kind, but we can't know for sure because you did not name the parameters in the method call. Provide the method signature so we can see for sure. Perhaps it takes an NSNumber or something.
Keep in mind that international users may be using a decimal separator other than . in which case values can get mixed up or just become nil when using intValue on a string.
For example, in the UK 1.23 is written 1,23, so the number 1.777 would be input by user as 1,777, which, as .intValue, will be 1777 not 1 (truncated).
I've made a macro that will convert input text to an NSNumber based on a locale argument which can be nil (if nil it uses device current locale).
#define stringToNumber(__string, __nullable_locale) (\
(^NSNumber *(void){\
NSLocale *__locale = __nullable_locale;\
if (!__locale) {\
__locale = [NSLocale currentLocale];\
}\
NSString *__string_copy = [__string stringByReplacingOccurrencesOfString:__locale.groupingSeparator withString:#""];\
__string_copy = [__string_copy stringByReplacingOccurrencesOfString:__locale.decimalSeparator withString:#"."];\
return #([__string_copy doubleValue]);\
})()\
)
If I understood you correctly, you need to convert your NSString to int? Try this peace of code:
NSString *stringWithNumberInside = [_returnedArguments objectAtIndex:2];
int number;
sscanf([stringWithNumberInside UTF8String], "%x", &flags);

NSString returning jibberish

Totally lost with this one. Here's my code:
theColor = [NSString stringWithFormat:#"white"];
NSLog(#"%s", theColor);
Which is returing:
†t†å
I must be doing something stupid, but can not figure it out for the life of me.
Change your print to:
NSLog(#"%#", theColor);
Hope it helps.
The thing is that %s expects a C-string (char array with a NULL terminator) and you are passing a NSString instance which is not the same as a C-string. The modifier you need in a format to print NSString content is %#.
%s is for printing C-style strings.
%# is for printing Objective-C objects (like NSString).
BTW: “theColor = [NSString stringWithFormat:#"white"];” – why not “theColor = #"white";”?
Greetings

RegExKitLite Expression Question

I'm having trouble coming up with an RegExKitLite expression that will match. I'm parsing a string and I want it to grab everything till it comes upon the first occurrence of a colon
What would be the expression in RegExKitLite to do that?
Thanks!
This regex will match everything from the start until (but excluding) the first colon:
^[^:]*
To include the first colon is as simple as putting it on the end:
^[^:]*:
So, to use either of those with RegexKitLite, you can do:
NSString * firstItem = [someString stringByMatching:#"^[^:]*" capture:0];
Note how there is no parentheses - since * is greedy you can simply use the negated class and use captured group 0 (i.e. the whole match).
It's worth noting that most languages will include functions that allow you to do this with a regular function, for example ListFirst(MyString,':') or MyString.split(':')[0]
I suspect Objective-C has something similar to this ... yep, see here
NSString *string = #"oop:ack:bork:greeble:ponies";
NSArray *chunks = [string componentsSeparatedByString: #":"];
To do this specifically with RegexKitLite, you'll need to do the following:
Add the RegexKitLite.h/.m files to your project
Import RegexKitLite.h into the file where you need to use regular expressions
Use the following to grab the stuff before the colon:
NSString * everythingBeforeTheColon = [someString stringByMatching:#"([^:]*):" capture:1];
I just updated my SO answer here, so I figured I'd use that to benchmark the standard foundation componentsSeparatedByString: and RegexKitLites componentsSeparatedByRegex:. The line of code inside the for() loop for each was (essentially):
NSString *string = #"oop:ack:bork:greeble:ponies";
for() { NSArray *chunks = [string componentsSeparatedByString: #":"]; }
for() { NSArray *chunks = [string componentsSeparatedByRegex: #":"]; }
Times returned were (time is in microseconds per operation):
componentsSeparatedByString: 3.96810us
componentsSeparatedByRegex: 2.46155us
EDIT:
I thought I'd go one better: How to use RegexKitLite to create a NSArray of NSArrays from a string containing multiple lines of colon separated data (ie, /etc/passwd). Modified from the comma separated value example in the RegexKitLite documentation. When finished, the variable splitLinesArray contains the finished product.
NSString *theString = #"a:b:c\n1:2:3\nX:Y:Z\n"; // An example string to work on.
NSArray *linesArray = [theString componentsSeparatedByRegex:#"(?:\r\n|[\n\v\f\r\\x85\\p{Zl}\\p{Zp}])"];
id splitLines[[linesArray count]];
NSUInteger splitLinesIndex = 0UL;
for(NSString *lineString in linesArray) { splitLines[splitLinesIndex++] = [lineString componentsSeparatedByRegex:#":"]; }
NSArray *splitLinesArray = [NSArray arrayWithObjects:splitLines count:splitLinesIndex];