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

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 ...

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!

how to get digits of a integer from NSString?

I am having a string like NSString *str = #"123".I want to fill the digits of this string into UIPickerView.But how to get the digits from this string?I added the following code
- (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component
{
int number = [str intValue];
if(component == 0)
{
}
else if(component == 1)
{
}
else
{
}
}
Please see this..
NSMutableArray *arrNumbers = [[NSMutableArray] alloc] initWithCapacity:[YOURSTRING length]];
for (i=0;i<[YOURSTRING length];i++)
{
  unichaar ch = [YOURSTRING characterAtIndex:i];
  NSLog(#"Processing charachter %c",ch);
  // If you really want
  [arrNumbers addObject:(id)ch];
}
Other solutions seem to be excessive, considering NSString is already an array of characters. More lightweight solution:
NSString *str = #"123";
for (int i = 0; i < [str length]; i++) {
int digit = [str characterAtIndex:i] - '0';
// do something with your digit
}
If you have it as a string you can just do
NSArray * digitStrings = [str componentsSeparatedByString:""];
And each element in the array would be a digit as a NSString.
not tested but you can give it a try, this is supposed to scan all numeric entries of your string.
-(NSArray*)getDigitsFromString:(NSString*)str{
NSMutableString *outpuString = [NSMutableString
stringWithCapacity:str.length];
NSScanner *scanner = [NSScanner scannerWithString:str];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[outpuString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSArray * digitStr = [outpuString componentsSeparatedByString:#""];
return digitStr;
}
NSMutableArray * digit=[[NSMutableArray alloc]init];
NSString *string = #"123456";
for (int i=0;i<[string length]; i++) {
NSString * newString = [string substringWithRange:NSMakeRange(i, 1)];
[digit addObject:newString];
}
NSLog(#"String %# ", digit)
One more answer which addresses more the idea of the original question by solving the problem of separating an int into it's digits:
NSString *numberString = #"68243";
int result[numberString.length];
NSInteger number = [numberString integerValue];
int j = numberString.length - 1;
while (j >= 0)
{
int power = pow(10, j);
int rest = (number % power);
result[j] = (number - rest)/power;
number = rest;
j--;
}

How to get response from .clp(CLIPS) file?

I am trying to load .clp file in my iPhone application. For that I am using below code
NSString *filePath = [[NSBundle mainBundle]
pathForResource:#"autodemo" ofType:#"clp"];
environment = CreateEnvironment();
char *clipsFileChar = (char *)[filePath cStringUsingEncoding:NSASCIIStringEncoding];
Load(clipsFileChar);
Reset();
Run(-1);
NSString *evalS = [NSString stringWithFormat:#"(find-all-facts ((?f state-list)) TRUE)"];
char * evalStr = (char *)evalS;
DATA_OBJECT obj;// = {0,-1};
// obj.type = STRING;
// obj.value = evalStr;
int i = Eval(evalStr, &obj);
NSLog(#"%d",i);
now when I run this code Eval(evalStr, &obj) gives me 0 every time.
I am using autodemo.clp file from this link.
So, how to make Eval() command work and how do I get response returned by clp file?
thanks,
below code solved my problem, hope it will help to someone else.. :)
InitializeEnvironment();
Clear();
NSString *filePath = [[NSBundle mainBundle]
pathForResource:#"autodemo" ofType:#"clp"];
char *clipsFileChar = (char *)[filePath cStringUsingEncoding:NSASCIIStringEncoding];
IncrementGCLocks();
Load(clipsFileChar);
Reset();
Run(-1);
DecrementGCLocks();
[self nextUIState];
- (void)nextUIState
{
DATA_OBJECT theDO;
NSString * evalS = #"(find-all-facts ((?f state-list)) TRUE)";
char *evalStr = (char *)[evalS cStringUsingEncoding:NSASCIIStringEncoding];
int j = EnvEval(GetCurrentEnvironment(), evalStr, &theDO);
NSLog(#"j = %d",j);
if(factDict)
{
[factDict release];
factDict = nil;
factDict = [[NSMutableDictionary alloc] init];
}
id value = [self objectForDataObject:&theDO];
NSLog(#"%#",[value description]);
}
-(id) objectForDataObject: (DATA_OBJECT*) arg
{
switch(arg->type)
{
case FACT_ADDRESS:
{
DATA_OBJECT data = { 0 };
struct fact* aFact = (struct fact*) arg->value;
if(EnvGetFactSlot(GetCurrentEnvironment(),aFact,(char*)[#"current" UTF8String],&data))
{
[factDict setObject:[self objectForDataObject: &data] forKey:#"current"];
[factDict retain];
}
return factDict;
}
case SYMBOL:
{
NSString *str = [NSString stringWithUTF8String: ValueToString(arg->value)];
if ([str isEqual: #"nil"]) return nil;
if ([str hasPrefix: #"<<<"] && [str hasSuffix: #">>>"])
{
return [self dataFromSymbolString: str];
}
return str;
}
case STRING:
{
return [NSString stringWithUTF8String: ValueToString(arg->value)];
}
case INTEGER:
{
return [NSNumber numberWithInt: ValueToInteger(arg->value)];
}
case FLOAT:
{
return [NSNumber numberWithDouble: ValueToDouble(arg->value)];
}
case EXTERNAL_ADDRESS:
{
return (id) arg->value;
}
case MULTIFIELD:
{
int i, count = GetpDOLength(arg);
NSMutableArray *args = [NSMutableArray arrayWithCapacity: count];
FIELD_PTR fptr = (FIELD_PTR) GetMFPtr(GetpValue(arg),GetpDOBegin(arg));
for(i = 0; i < count; ++i, ++fptr)
{
DATA_OBJECT dobj;
dobj.type = fptr->type;
dobj.value = fptr->value;
[args addObject: [self objectForDataObject: &dobj]];
}
return args;
}
default:
return nil;
}
}
If you find out any other and better way(ofcourse there is), please let me know. :)

String and array

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
}