String and array - iphone

NSString *depositOverTotalRwy = [NSString stringWithFormat:#"%#", [deposit text]];
NSArray *components = [depositOverTotalRwy
componentsSeparatedByString:#"/"];
NSString *firstThird = [components objectAtIndex:0];
if ([firstThird isEqualToString: #"1"]) {
NSLog(#"wet");
}
if ([firstThird isEqualToString:#"2"]) {
NSLog(#"snow");
}
if ([firstThird isEqualToString:#"3"]) {
NSLog(#"ice");
}
NSString *secThird = [components objectAtIndex:1];
if ([secThird isEqualToString: #"1"]) {
NSLog(#"wet");
}
if ([secThird isEqualToString:#"2"]) {
NSLog(#"snow");
}
if ([secThird isEqualToString:#"3"]) {
NSLog(#"ice");
}
NSString *thirdThird = [components objectAtIndex:2];
if ([thirdThird isEqualToString: #"1"]) {
NSLog(#"wet");
}
if ([thirdThird isEqualToString:#"2"]) {
NSLog(#"snow");
}
if ([thirdThird isEqualToString:#"3"]) {
NSLog(#"ice");
}
dep.text = [NSString stringWithFormat:#"%# over %# over %#", firstThird, secThird, thirdThird];
Hi guys,
I have a problem. when I set the label (dep.text), I get the number instead of wet, snow or ice. it works in the console (NSlog).
I know it must be some error in the logic but i'm not able to find it. Thanks in advance.

Instead of putting NSLog(#"snow"); assign firstThird=#"snow"

it looks to me as it the objects within components are #"1", #"2" or #"3".
dep.text is reflecting that
for dep.text to resemble what you wish, you need to set the strings, something like -
thirdThird = #"wet";
thirdThird = #"snow";
thirdThird = #"ice";
inside the conditions of course
}

Related

All Pairs of 0 remove from NSString in Objective-C

I want to remove all occurrence of 0 pairs before appearing any digit(1-9) from NSString
if 000001234000 required 01234000
if 0000123400 required 123400
if 012340000 required 012340000
if 00000012 required 12
Can anyone help ? thanks.
Perhaps not the most elegant solution (but only trims leading '00'):
- (NSString *)trimLeadingDoubleZerosFrom:(NSString *)str {
if (str.length > 1 ) {
if ([[str substringWithRange:NSMakeRange(0, 2)] isEqualToString:#"00"]) {
return [self trimLeadingDoubleZerosFrom:[str substringFromIndex:2]];
}
}
return str;
}
Seems to work for your examples:
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"000001234000"]);// returns 01234000
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"0000123400"]); // returns 123400
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"012340000"]); // returns 012340000
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"00000012"]); // returns 12
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"12"]); // returns 12
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"02"]); // returns 02
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"2"]); // returns 2
NSString *MyString = #"00000123050060007";
NSString *NewString = [self RemovePairOfZero:MyString];
NSLog(#"OUTPUT:: %#", NewString);
- (NSString *)RemovePairOfZero:(NSString *)Param
{
if ([Param length] > 1 )
{
if ([[Param substringWithRange:NSMakeRange(0, 2)] isEqualToString:#"00"])
{
return [self RemovePairOfZero:[Param substringFromIndex:2]];
}
}
return Param;
}
//2013-09-24 13:15:58.527 Test[1584:907] OUTPUT:: 0123050060007
NSString* a = #"00000123";
while ([a hasPrefix:#"00"]) {
a = [a stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:#""];
}
You can try using stringByreplacingOccurancesOfString:#"00" withString:#""
NSString *s= #"00000123";
NSLog(#"%#",s);
s = [s stringByReplacingOccurrencesOfString:#"00" withString:#"."];
NSLog(#"%#",s);
Try this one..
That can be done by simply replacing #"00" with #""
NSString *string = #"00000123";
string = [string stringByReplacingOccurrencesOfString:#"00" withString:#""];
Hope that helps!

How to remove starting 0's in uitextfield text in iphone sdk

Code Snippet:
NSString *tempStr = self.consumerNumber.text;
if ([tempStr hasPrefix:#"0"] && [tempStr length] > 1) {
tempStr = [tempStr substringFromIndex:1];
[self.consumerNumbers addObject:tempStr];>
}
I tried those things and removing only one zero. how to remove more then one zero
Output :001600240321
Expected result :1600240321
Any help really appreciated
Thanks in advance !!!!!
Try to use this one
NSString *stringWithZeroes = #"001600240321";
NSString *cleanedString = [stringWithZeroes stringByReplacingOccurrencesOfString:#"^0+" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, stringWithZeroes.length)];
NSLog(#"Clean String %#",cleanedString);
Clean String 1600240321
convert string to int value and re-assign that value to string,
NSString *cleanString = [NSString stringWithFormat:#"%d", [string intValue]];
o/p:-1600240321
You can add a recursive function that is called until the string begin by something else than a 0 :
-(NSString*)removeZerosFromString:(NSString *)anyString
{
if ([anyString hasPrefix:#"0"] && [anyString length] > 1)
{
return [self removeZerosFromString:[anyString substringFromIndex:1]];
}
else
return anyString;
}
so you just call in your case :
NSString *tempStr = [self removeZerosFromString:#"000903123981000"];
NSString *str = #"001600240321";
NSString *newStr = [#([str integerValue]) stringValue];
If the NSString contains numbers only.
Other wise use this:
-(NSString *)stringByRemovingStartingZeros:(NSString *)string
{
NSString *newString = string;
NSInteger count = 0;
for(int i=0; i<[string length]; i++)
{
if([[NSString stringWithFormat:#"%c",[string characterAtIndex:i]] isEqualToString:#"0"])
{
newString = [newString stringByReplacingCharactersInRange:NSMakeRange(i-count, 1) withString:#""];
count++;
}
else
{
break;
}
}
return newString;
}
Simply call this method:-
NSString *stringWithZeroes = #"0000000016909tthghfghf";
NSLog(#"%#", [self stringByRemovingStartingZeros:stringWithZeroes]);
OutPut: 16909tthghfghf
Try the `stringByReplacingOccurrencesOfString´ methode like this:
NSString *new = [old stringByReplacingOccurrencesOfString: #"0" withString:#""];
SORRY: This doesn't help you due to more "0" in the middle part of your string!

String not getting split giving unrecognized selector error

Trying to split the string in to array, but it is giving error "[__NSArrayI componentsSeparatedByString:]: unrecognized selector sent to instance 0x11741b20'". The string contains the value, that comes from first index of array then the string needs to be split and store in array.
This is array value.
mcommarr:(
":comment",
":comment",
":comment"
NSString *strr = [[NSString alloc]init];
strr = [self.mCommArr objectAtIndex:indexVal];
NSArray *arr2 = [str componentsSeparatedByString:#","];
Here is the complete method in which i am using this.
-(void)loadData:(int)indexVal;
{
indexVal=serialIndexVal;
serialIndexVal++;
NSLog(#"arrLike:%d", [self.mArrLike count]);
NSLog(#"arrPid:%d", [self.mArrPid count]);
status = [NSString stringWithFormat:#"get"];
[self.mButtonsStatusDict setObject:status forKey:#"status"];
[self.mButtonsPidDict setObject:[self.mArrPid objectAtIndex:indexVal] forKey:#"pid"];
[self.activityIndicator startAnimating];
#try
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSString *status = [NSString stringWithFormat:#"get"];
[self.mButtonsStatusDict setObject:status forKey:#"status"];
[self.mButtonsPidDict setObject:[self.mArrPid objectAtIndex:indexVal] forKey:#"pid"];
self.mButtonsCommentsDict = [MyEventApi showComments:self.mButtonsPidDict];
self.mButtonsDict = [MyEventApi likeDislike:self.mButtonsUidDict post:self.mButtonsPidDict postStatus:self.mButtonsStatusDict];
dispatch_sync(dispatch_get_main_queue(), ^{
[self.activityIndicator stopAnimating];
NSLog(#"buttons data dict:%#", self.mButtonsDict);
if([self.mButtonsDict count] == 0)
{
NSLog(#"server problem no response");
[self.mArrLike addObject: #"0"];
[self.mArrDislike addObject: #"0"];
}else{
[self.mArrLike addObject: [self.mButtonsDict valueForKey:#"like"]];
[self.mArrDislike addObject: [self.mButtonsDict valueForKey:#"dislike"]];
}
if([self.mButtonsCommentsDict count] == 0)
{
NSLog(#"server problem no response");
[self.mCommArrTot addObject: #"0"];
}
else{
self.dictComm = [self.mButtonsCommentsDict valueForKey:#"comments"];
[self.mCommArr addObject:[self.dictComm valueForKey:#"comment"]];
NSLog(#"count:%d",[self.mCommArr count]);
// NSString *strTot = [NSString stringWithFormat:#"%d",tot];
// [self.mCommArrTot addObject:strTot];
NSLog(#"dictcomm:%#", self.dictComm );
NSLog(#"mcommarr:%#", [self.mCommArr objectAtIndex:indexVal]);
strr = [[NSString alloc]init];
strr = [self.mCommArr objectAtIndex:indexVal];
//NSString *strr = [[NSString stringWithFormat:#"%#", [self.mCommArr objectAtIndex:indexVal]];
// NSArray *arr1 = [self string:strr];
// NSArray *splitArray=[self.mCommArr[0] componentsSeparatedByString:#","];
//[strr componentsSeparatedByString:#","];
// NSLog(#"arrSep:%#", arr1);
//int count = [arr1 count];
//NSLog(#"arrcount:%d", count);
// NSString *strTot = [NSString stringWithFormat:#"%d",count];
// [self.mCommArrTot addObject:strTot];
//NSLog(#"mcommarrtot:%#", [self.mCommArrTot objectAtIndex:indexVal]);
}
// NSLog(#"arrLike:%#", [self.mArrLike objectAtIndex:indexVal]);
// NSLog(#"arrDisLike:%#", [self.mArrLike objectAtIndex:indexVal]);
[self.mPublicFriendTable reloadData];
});
});
}
#catch (NSException *exception) {
NSLog(#"main: Caught %#: %#", [exception name], [exception reason]);
}
#finally {
}
}
It get killed when try to split. Why so, i am not getting. If anyone has faced such situation please guide what is wrong her.
You can split the string into an NSArray like below...
NSString *yourString = #"comment,comment,comment";
NSArray *strArray = [yourString componentsSeparatedByString:#","];
NSLog(#"\n\n Array is ==>> %#",strArray);
"[__NSArrayI componentsSeparatedByString:]:
Your error says you tried to send the above method to NSArray, which doesn't has.
As you want to split the array at index 0. you should probably do as :
NSArray *splitArray=[yourArray[0] componentsSeparatedByString:#","];
Here yourArray is the array that you get from Server.
NSString *strr = [[NSString stringWithFormat:#"%#", [self.mCommArr objectAtIndex:indexVal]];
NSArray *arr2 = [strr componentsSeparatedByString:#","];
I think you are passing str right now, which can be an array (as your error points out).
Let me know the results.

How to parse JSON and have 2 final arrays of data

I am parsing an itunes rss feed with JSON but I have run into a problem. The following code is running properly for one the movieName output but I still don't get the movieSummary output.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
feed = [allDataDictionary objectForKey:#"feed"];
arrayOfEntry = [feed objectForKey:#"entry"];
for (NSDictionary *dictionTitle in arrayOfEntry) {
NSDictionary *title = [dictionTitle objectForKey:#"title"];
NSString *labelTitle = [title objectForKey:#"label"];
[arrayLable addObject:labelTitle];
NSDictionary *summary = [dictionTitle objectForKey:#"summary"];
NSString *labelSummary = [summary objectForKey:#"label"];
[arraySummary addObject:labelSummary];
}
movieName.text = [arrayLable objectAtIndex:0];
movieSummary.text = [arraySummary objectAtIndex:0]; //This is not displaying
}
Here is the link that I am parsing: http://itunes.apple.com/us/rss/topmovies/limit=300/json
I run into this situation a lot. I use something like this. Replace your code
NSString *labelTitle = [title objectForKey:#"label"];
[arrayLable addObject:labelTitle];
with
NSString * labelTitle = [ [ title objectForKey:#"label" ] ifNullThenNil ] ;
[ arrayLabel addObject:labelTitle ? labelTitle : #"" ] ; // you could also use #"<unknown>" or similar instead of #""
where -ifNullThenNil is provided via category:
#implementation NSObject (IfNullThenNil)
-(id)ifNullThenNil { return self ; }
#end
#implementation NSNull (IfNullThenNil)
-(id)ifNullThenNil { return nil ; }
#end
The problem was that when I was adding the strings to the Array that it sometimes contained NULL's thus the following code helped me out
if ([[arrayName objectAtIndex:0] isKindOfClass:[NSNull class]]) {
labelName.text = #"This is NULL";
} else {
[arrayName addObject:labelName];
}
if ([[arraySummary objectAtIndex:0] isKindOfClass:[NSNull class]]) {
labelSummary.text = #"This is NULL";
} else {
[arraySummary addObject:labelSummary];
}

How can I verify if a String has a null value?

sorry but i'm still struggling to make this code working. It works if with a 2 digits number but it crashes with a single digit number. How can I verify if the NSString *secDigit has a value or is null. I hope my question is clear. Thanks in advance.
NSString *depositOverTotalRwy = [NSString stringWithFormat:#"%#", [deposit text]];
NSArray *components = [depositOverTotalRwy
componentsSeparatedByString:#"/"];
NSString *firstThird = [components objectAtIndex:0];
char firstChar = [firstThird characterAtIndex:0];
char secChar = [firstThird characterAtIndex:1];
NSString *firstDigit = [NSString stringWithFormat:#"%c",firstChar];
NSString *secDigit = [NSString stringWithFormat:#"%c", secChar];
NSLog(#" i'm %#", firstDigit);
NSLog(#" i'm %#", secDigit);
if ([firstDigit isEqualToString: #"1"]) {
firstDigit=#"wet";
NSLog(#"wet");
}
if ([firstDigit isEqualToString: #"2"]) {
firstDigit=#"wet";
NSLog(#"snow");
}
if ([firstDigit isEqualToString: #"3"]) {
firstDigit=#"wet";
NSLog(#"ice");
}
if ([secDigit isEqualToString: #"1"]) {
secDigit=#"wet";
NSLog(#"wet");
}
if ([secDigit isEqualToString: #"2"]) {
secDigit=#"snow";
NSLog(#"snow");
}
if ([secDigit isEqualToString: #"3"]) {
secDigit=#"ice";
NSLog(#"ice");
}
thanks to all of you..... here my code (working now):
NSString *depositOverTotalRwy = [NSString stringWithFormat:#"%#", [deposit text]];
NSArray *components = [depositOverTotalRwy
componentsSeparatedByString:#"/"];
NSString *firstThird = [components objectAtIndex:0];
char firstChar = [firstThird characterAtIndex:0];
NSString *firstDigit = [NSString stringWithFormat:#"%c",firstChar];
NSLog(#" i'm %#", firstDigit);
if ([firstDigit isEqualToString: #"1"]) {
firstDigit=#"wet";
NSLog(#"wet");
}
if ([firstDigit isEqualToString: #"2"]) {
firstDigit=#"wet";
NSLog(#"snow");
}
if ([firstDigit isEqualToString: #"3"]) {
firstDigit=#"wet";
NSLog(#"ice");
}
if ([firstThird length] >1) {
char secChar = [firstThird characterAtIndex:1];
NSString *secDigit = [NSString stringWithFormat:#"%c", secChar];
if ([secDigit isEqualToString: #"1"]) {
secDigit=#"wet";
NSLog(#"wet");
}
if ([secDigit isEqualToString: #"2"]) {
secDigit=#"snow";
NSLog(#"snow");
}
if ([secDigit isEqualToString: #"3"]) {
secDigit=#"ice";
NSLog(#"ice");
}
}
I guess you code crashes in this line:
char secChar = [firstThird characterAtIndex:1];
This is because you try to access a character outside of the string bounds. You need to guard against this by checking the length of the string first:
if ([firstThird count] > 1) {
// String has 2 or more characters, do all the stuff that involves
// a second character.
char secChar = [firstThird characterAtIndex:1];
NSString *secDigit = [NSString stringWithFormat:#"%c", secChar];
if ([secDigit isEqualToString: #"1"]) {
secDigit=#"wet";
NSLog(#"wet");
}
}
But I'd also like to recommend to not use an NSString here, as you already have a char. Just do something like this:
if ([firstThird count] > 1) {
// String has 2 or more characters, do all the stuff that involves
// a second character.
char secChar = [firstThird characterAtIndex:1];
if (secChar == '1') {
secDigit=#"wet";
NSLog(#"wet");
}
}
I think this is what you are looking for:
char secChar;
if(firstThird.length > 1)
{
secChar = [firstThird characterAtIndex:1];
}
According to this
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
NSString "Raises an NSRangeException if index lies beyond the end of the receiver"
So, your code:
char secChar = [firstThird characterAtIndex:1];
Is the problem (you should see that in the debugger Console)
Check the length first with
if ([firstThird length] < 2) {
// handle the case where it is one digit
}
You can check number of characters in a string using NSString length. and modify your code
as
NSString *depositOverTotalRwy = [NSString stringWithFormat:#"%#", #"23"];
NSArray *components = [depositOverTotalRwy
componentsSeparatedByString:#"/"];
NSString *firstThird = [components objectAtIndex:0];
unichar firstChar;
unichar secChar;
if([firstThird length]>1){
firstChar = [firstThird characterAtIndex:0];
secChar = [firstThird characterAtIndex:1];
} else {
firstChar = [firstThird characterAtIndex:0];
secChar = 0;
}
switch (firstChar) {
case '1': /* Do your stuff*/break;
case '2': /* Do your stuff*/break;
case '3': /* Do your stuff*/break;
default:
break;
}
switch (secChar) {
case '1': /* Do your stuff*/break;
case '2': /* Do your stuff*/break;
case '3': /* Do your stuff*/break;
default:
break;
}
you can use unichar instead of char. And can perform check in switch statements.
If you use char, a casting is done from unichar to char and for some characters you may lose actual value. So it is safe to use unichar...
If you want to convert unichar to string simply code
NSString * stringChar = [NSString StringWithFormat:#"%C",unicharVariable];
Thats it ...