How can i check string contains unknown character? - ios

I am calling webservice in the response i am getting the string.
When i print the string in NSLog it return empty string and When i check the length it returns 1.
So my problem is that how can i check the string is empty or not.
#define CHECK_NA_STRING(str) (str == (id)[NSNull null] || [str length] == 0)?#"N/A":str
NSLog(#"%#",CHECK_NA_STRING([dict objectForKey:#"ADDRESS_A"])); // nothing empty string
NSLog(#"%d",[CHECK_NA_STRING([dict objectForKey:#"ADDRESS_A"]) length]); // return 1
So how can i check that string is empty or not?
Thanks.

So the string is just a space? Then it will still have a length of 1.
Try:
NSString* string = ...;
if([string isKindOfClass:[NSString class]])
{
NSCharacterSet* invertedWhitespaceSet = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet];
const NSRange nonEmptyCharacterRange = [string rangeOfCharacterFromSet:invertedWhitespaceSet options:NSCaseInsensitiveSearch];
if(nonEmptyCharacterRange.location == NSNotFound)
{
// Empty invalid string
}
else
{
// Non-empty valid string
}
}

The string is not considered empty if it contains a binary zero (null character). For instance, try this code:
#define CHECK_NA_STRING(str) (str == (id)[NSNull null] || [str length] == 0)?#"N/A":str
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:#"\0" forKey:#"ADDRESS_A"];
NSLog(#"%#",CHECK_NA_STRING([dict objectForKey:#"ADDRESS_A"])); // nothing empty string
NSLog(#"%d",[CHECK_NA_STRING([dict objectForKey:#"ADDRESS_A"]) length]); // return 1
Nothing will print for the first NSLOG, but the second will print a "1". Indeed the string is one character long; it just messes up your NSLOG.
You probably want to test for some valid range of responses, or some invalid range. Perhaps, you could use a regular expression.

Related

How to get the first alphabet character of a string in iOS

I have an example NSString in iOS
NSString* str = #"-- This is an example string";
I want to get the first alphabet letter. The result of above situation is letter "T" from word "This". Some characters before letter "T" is not alphabet letter so it returns the first alphabet letter is "T".
How can I retrieve it? If the string not contain any alphabet letter, it can return nil.
Besides, the result can be a NSRange
NSRange range = [string rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
First create a NSCharecterSet as a global variable and write this code
-(void)viewDidLoad{
NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"]
s = [s invertedSet];
NSString *myString = #"--- This is a string";
NSArray *arrayOfStrings = [myString componentsSeparatedByString:#" "];
for(int i=0;i<arrayOfStrings.count){
NSString *current = [arrayOfStrings objectAtIndex:i];
char c = [self returnCharacter:current];
if(c == nil){
//that means first word is not with alphabets;
}
else {
NSLog(#"%c",c);
//your output.
}
}
}
And here is the method
-(char)returnChracter:(NSString*)string{
NSRange r = [string rangeOfCharacterFromSet:s];
if (r.location != NSNotFound) {
NSLog(#"the string contains illegal characters");
return nil;
}
else {
//string contains all alphabets
char firstLetter = [string charAtIndex:0];
return firstLetter;
}
}
You can use the following function. Pass a string and get first character as a string.
-(NSString*)getFirstCharacter:(NSString*)string
{
for(int i=0;i<string.length;i++)
{
unichar firstChar = [string characterAtIndex:i];
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
if ([letters characterIsMember:firstChar]) {
return [NSString:stringWithFormat:#"%c",firstChar];
}
}
return nil;
}

Hex String Detected as Base64

I'm passing Hex string to this method but it still detects the string as base64.
My string is: 546869732069732073696d706c6520737472696e672e
+(BOOL)isBase64Data:(NSString *)input
{
input=[[input componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString:#""];
if ([input length] % 4 == 0) {
static NSCharacterSet *invertedBase64CharacterSet = nil;
if (invertedBase64CharacterSet == nil) {
invertedBase64CharacterSet = [[NSCharacterSet
characterSetWithCharactersInString:
#"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="]
invertedSet];
}
BOOL isbase64 = [input rangeOfCharacterFromSet:invertedBase64CharacterSet
options:NSLiteralSearch].location == NSNotFound;
return isbase64;
}
return NO;
}
Have followed several links on net with above code marked true. But somehow it's not working with the string I provided.

How to pad strings to a fixed width with NSMutableString?

I'm trying to write a string to a text file. That text file will then be read by another program. That second program is expecting the different "fields" in the text file to be a fixed width. Therefore, when I write the text file with my app, I will need to add spaces between my actual data to get everything to line up correctly. How do I get these spaces added?
So far, I've tried writing a function that takes a source string and a target length as input. If the target is longer than the source, it just appends " ". Code for this routine is below:
- (NSString *) makeStringFrom:(NSString *)source withLength:(NSInteger)length
{
// Method to add spaces to the end of a string to get it to a certain length
if ([source length] > length)
{
// String is too long - throw warning and send it back
NSLog(#"Warning - string is already longer than length supplied. Returning source string");
return source;
}
else if ([source length] == length)
{
// String is already correct length, so just send it back
return source;
}
else
{
// String is too short, need to add spaces
NSMutableString *newString = [[NSMutableString alloc] initWithString:source];
NSLog(#"newString initial length = %d",[newString length]);
for (int current = [source length]; current < length; current ++)
{
[newString stringByAppendingString:#" "];
NSLog(#"hit");
}
NSLog(#"target length = %d. newString length = %d",length,[newString length]);
return newString;
}
}
This apparently doesn't work. The length of the string I'm getting back in the return isn't changing any from the length of the supplied string, even when the NSLog(#"hit"); runs multiple times.
There's a stringByPaddingToLength:withString:startingAtIndex: method on NSString that does just this.
You did a silly mistake here
[newString stringByAppendingString:#" "];
This returns a new string, and it doesnot effect the caller object. You need to store it
newString=[newString stringByAppendingString:#" "];
or simply
[newString appendString:#" "];
You want to change:
[newString stringByAppendingString:#" "];
into:
newString = [newString stringByAppendingString:#" "];

if statement issue in drawRect

Yes, yes. Shame on me. I am trying to draw in UIView and my code is:
NSString *str;
if(kmObj.metal!=#"" && kmObj.metalName2!=#"" && kmObj.metalname3!=#"")
{
str=[NSString stringWithFormat:#"%# + %# + %#",kmObj.metal,kmObj.metalName2,kmObj.metalname3];
}
if(kmObj.metal!=#"" && kmObj.metalName2!=#"" && kmObj.metalname3==#"")
{
str=[NSString stringWithFormat:#"%# + %#",kmObj.metal,kmObj.metalName2];
}
if(kmObj.metal!=#"" && kmObj.metalName2==#"" && kmObj.metalname3==#"")
{
str=[NSString stringWithFormat:#"%#",kmObj.metal];
}
[str drawAtPoint:CGPointMake(10.0,234.0)
forWidth:200
withFont:[UIFont systemFontOfSize:20.0]
minFontSize:20.0
actualFontSize:NULL
lineBreakMode:UILineBreakModeTailTruncation
baselineAdjustment:UIBaselineAdjustmentAlignBaselines];
So, this code suppose to check if the Object contains more than one metal name record. If so, than it has to format string to form: Au+Ag+Cu ... My problem is that in output draw I can't get rid of the + signs where I don't need them. Is there something wrong in my if statement?
Instead of if (string != #""), use ![string isEqualToString:#""] or perhaps ([string length] > 0). You need to make sure you are performing a value comparison, not a pointer comparison.
Anyway, I would write code like this:
NSString *outputString = #"";
if ([firstString length] > 0) {
outputString = [outputString stringByAppendingString:firstString];
}
if ([secondString length] > 0) {
outputString = [outputString stringByAppendingFormat:#" + %#", secondString];
}
if ([thirdString length] > 0) {
outputString = [outputString stringByAppendingFormat:#" + %#", thirdString];
}
With this technique, you check each string individually, and only include a plus sign when you know another valid string will follow it.
String comparisons should take the form: [stringA isEqualToString:stringB]
From the docs: When you know both objects are strings, this method is a faster way to check equality than isEqual:
Plus, == for strings is weird anyways - they are non-primitives and you're wanting a value comparison.
Also, you should take into account the possibility of having nil and/or [NSNull null] values (depending on where these values are sourced). Your current test of whether or not they are equal to empty strings doesn't take this into account.
Did you mean that you don't want the "+" sign? Then don't put it in your NSString.
So instead of
str = [NSString stringWithFormat:#"%# + %# + %#",kmObj.metal,kmObj.metalName2,kmObj.metalname3];
do
str = [NSString stringWithFormat:#"%# %# %#",kmObj.metal,kmObj.metalName2,kmObj.metalname3];
also use [kmObj.metal isEqualToString:#""] for your string comparison

iOS can't check if object is null

So I have the following code:
- (IBAction)doSomething
{
if (txtName.text != (id)[NSNull null] || txtName.text.length != 0 ) {
NSString *msg = [[NSString alloc] initWithFormat:#"Hello, %#", txtName.text];
[lblMessage setText:msg];
}
}
txtName is an UITextField, what I'm doing wrong? I'm trying to display some text only when the user types something in the box.
Best Regards,
Text in a text field is a NSString instance or nil value, it is never equal to the instance of NSNull class (which is not the same as nil). So as 1st comparison is always true then the whole if-condition evaluates to true and message appears.
You could correct your if condition to
if (txtName.text != nil && txtName.text.length != 0 )
or, as sending length message to the nil will return 0 anyway just have
if (txtName.text.length != 0 )
although I usually use the 1st option with 2 comparisons
if (txtName.text != (id)[NSNull null] || txtName.text.length != 0 ) {
Read it as "If the text is null or the length is not 0"
txtName.text is never nil (you can just compare against nil for a null check, by the way) - the text box always holds some text, even if it's empty. So the first disjunct is always true, and the box will always appear.
I got the same problem like you. This problem relates to NSNull class. And here is my code to check object is null.
NSString* text;
if([text isKindOfClass:[NSNull class]])
{
//do something here if that object is null
}
Hope this can help.
#define SAFESTRING(str) ISVALIDSTRING(str) ? str : #""
#define ISVALIDSTRING(str) (str != nil && [str isKindOfClass:[NSNull class]] == NO)
#define VALIDSTRING_PREDICATE [NSPredicate predicateWithBlock:^(id evaluatedObject, NSDictionary *bindings) {return (BOOL)ISVALIDSTRING(evaluatedObject);}]
SAFESTRING(PASS_OBJECT OR STRING);
Solution found! ![txtName.text isEqualToString:#""]
- (IBAction)doSomething
{
if (![txtName.text isEqualToString:#""]){
NSString *msg = [[NSString alloc] initWithFormat:#"Hello, %#", txtName.text];
[lblMessage setText:msg];
}
}
Please try this:
when value of myObj is nil or < null>
if([myObj isEqual:[NSNull class]] || !myObj) {
// your code
}

Resources