After extracting a string from JSON response:
NSString *responseMessage = [NSString stringWithFormat:#"%#",[[JSON objectForKey:#"Response"]valueForKey:#"Message"]];
NSLog(#"<%#>",responseMessage);
It looks like this:
<(
"not found"
)>
This is the relevant code:
So when I try to compare it, isEqualToString returns always false
([responseMessage isEqualToString:#"not found"])?NSLog(#"They are equal"):NSLog(#"They are different");//they are different
How to get rid of these parentheses to better compare the two strings? Thanx in advance.
It looks like you have an array here (which in Objective-C will print as a list with parentheses).
What is the source JSON string?
If it is an array, you want to iterate over its elements, or maybe just pull out the first one.
You could try using the NSRegularExpression to remove if any brackets existing in your code. You can find different combinations for regular expressions to use.
NSString *expression = #"\\s+\\([^()]*\\)";
while ([responseMessage rangeOfString:expression options:NSRegularExpressionSearch|NSCaseInsensitiveSearch].location!=NSNotFound)
{
responseMessage = [responseMessage stringByReplacingOccurrencesOfString:expression withString:#"" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch range:NSMakeRange(0, [responseMessage length])];
}
NSLog(#"returnResponse %#",responseMessage);
Related
i have a NSString with parentheses in it.
I would like to remove the Text inside of the parentheses.
How to do that? ( In Objective-C )
Example String:
Tach auch. (lockeres Ruhrdeutsch) Und Hallo!
I would like to Remove "(lockeres Ruhrdeutsch)" from the String,
but the Strings i have to edit are always different.
How can i remove the String betweeen "(" and ")"?
Best Regards
Use regular expression:
NSString *string = #"Tach auch. (lockeres Ruhrdeutsch) Und Hallo!";
NSString *filteredString = [string stringByReplacingOccurrencesOfString:#"\\(.*\\)"
withString:#""
options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
NSLog(#"%#", filteredString);
If you want to consider also a whitespace character after the closing parenthesis, add \\s? to the end of the regex pattern.
Here is the function you can call to get your required string:
-(NSString*)getStringWithBlankParaFrom:(NSString*)oldStr{
NSArray*strArray1=[oldStr componentsSeparatedByString:#"("];
NSString*str2=[strArray1 objectAtIndex:1];
NSArray*strArray2 =[str2 componentsSeparatedByString:#")"];
NSString*strToReplace=[strArray2 objectAtIndex:0];
return [oldStr stringByReplacingOccurrencesOfString:strToReplace withString:#""];
}
This function is valid for the string which contains one pair of parentheses**()**
You can change it as per your requirement.
Hope this helps!
The following code to conditionally concatenate strings for a dictionary seems to work up to the point where I try to place the concatenated result in the dictionary. Can anyone see the error?
NSDictionary *jsonDictionary;
NSString* dictString = #"#\"first\":first,#\"last"
NSString *dictString2=dictString;
if (date.length>0&&![date isKindOfClass:[NSNull class]]) {
//only include this key value pair if the value is not missing
dictString2 = [NSString stringWithFormat:#"%#%s", dictString, "#\"date\":date"];
}
jsonDictionary = #{dictString2}; //syntax error. Says expected colon but that does not fix anything
The syntax for creating an NSDictionary using object literals is:
dictionary = #{key:value}
(and optionally, it can contain multiple key/value pairs separated by commas, but never mind that right now.)
Where "key" and "value" are both NSObjects.
Your line that is throwing the error only contains 1 thing. The contents of a the string in dictString2 has nothing to do with it.
It looks to me like you are trying to build a JSON string manually. Don't do that. Use NSJSONSerialization. That class has a method dataWithJSONObject that takes an NSObject as input and returns NSData containing the JSON string. That's how you should be creating JSON output.
Creating an NSDictionary with values that may be null:
NSDictionary *dict = #{
#"key" : value ?: [NSNull null],
};
When serializing a dictionary, NSNulls are translated to null in the JSON.
If you want to exclude such keys completely, instead of having them with a null value, you'll have to do more work. The simplest is to use an NSMutableDictionary and test each value before adding it.
I'm facing a problem when I try to remove a character in a 'NSString'. The character is a backend (\n).
My 'NSString' is for example like this :
My text is
also in a second line
And I want to get all in one line like this :
My text is also in a second line
The problem is I don't know how to change this...
I tried to locate the '\n' characters with a loop :
for (int delete = 0; delete < myString.length; delete++)
{
if ([myString characterAtIndex:delete] == 10)
{
[myString stringByReplacingCharactersInRange:NSMakeRange(delete,0) withString:#" "];
}
}
Or things like :
myString = [myString stringByReplacingOccurrencesOfString:#"\r" withString:#" "];
(I see that \r could be the backend in a nslog...)
Nothings work..
Thank you for your help in advance !
myString = [myString stringByReplacingOccurrencesOfString:#"\n" withString:#""];
is correct.
If it doesn't work, then the assumption that there is a combination of "\" and "n" characters is wrong.
Do not use NSLog. NSLog already applies carriage returns to the string. Instead put a breakpoint on the line where we call stringByReplacing... and then hover over the myString. Wait a second or two and you will see the "original unformatted content"...this way you can check what you are really trying to replace..
I have the following NSString:
productID = #"com.sortitapps.themes.pink.book";
At the end, "book" can be anything.... "music", "movies", "games", etc.
I need to find the third period after the word pink so I can replace that last "book" word with something else. How do I do this with NSRange? Basically I need this:
partialID = #"com.sortitapps.themes.pink.";
You can try a backward search for the dot and use the result to get the desired range:
NSString *str = #"com.sortitapps.themes.pink.book";
NSUInteger dot = [str rangeOfString:#"." options:NSBackwardsSearch].location;
NSString *newStr =
[str stringByReplacingCharactersInRange:NSMakeRange(dot+1, [str length]-dot-1)
withString:#"something_else"];
You can use -[NSString componentsSeparatedByString:#"."] to split into components, create a new array with your desired values, then use [NSArray componentsJoinedByString:#"."] to join your modified array into a string again.
Well, although this isn't a generic solution for finding characters, in your particular case you can "cheat" and save code by doing this:
[productID stringByDeletingPathExtension];
Essentially, I'm treating the name as a filename and removing the last (and only the last) extension using the NSString method for this purpose.
I have a NSString in this format:
"Key1-Value1,Key2-Value2,Key3-Value3,..."
I need only keys (with a space after every comma):
Key1, Key2, Key3, etc.
I thought to create an array of components from the string using the comma as separator, and after, for every component, extract all characters since the "-"; then I'd serialize the array elements. But I fear this could be very heavy about performances.
Do you know a way to do this using regular expressions?
The regex will greatly depend on the data you are using. For example if the key or value is allowed to be all numbers, or allowed to contain space and punctuation, you would need to modify the regex. For your current example however this will work.
NSString *example = #"Key1-Value1,Key2-Value2,Key3-Value3,...";
NSString *result = [example stringByReplacingOccurrencesOfString:#"(\\w+)-(\\w+),?"
withString:#"$1, "
options:NSRegularExpressionSearch
range:NSMakeRange(0, [example length])];
result = [result stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#", "]];
NSLog(#"%#", result);