clean way to add query string to NSString? - iphone

So I have a NSString with a url like this:
NSString stringWithFormat:#"/reading.php?title=blah&description="blah"&image_url=blah... "
what is the best way to append query string to this string? is there a dictionary kind of way to do this?

What you want to do is this.
[NSString stringWithFormat:#"/reading.php?title=blah&description=%#&image_url=blah... ",blah];
Basically %# in the context meaning that you'll pass use a dynamic value which will be a string.

How about a category?
This is not great but for a first pass should give you something to get started
#interface NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
#end
#implementation NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
{
NSMutableString *params = [NSMutableString string];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
[params appendFormat:#"%#=%#&", key, obj];
}];
return [params copy];
}
#end
This would end up with something like:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:#"42", #"special_number", #"value", #"another", nil];
NSString *myString = [NSString stringWithFormat:#"/reading.php?%#", [params URLParamsValue]];
NSLog(#"%#", myString);
#=> 2012-03-20 23:54:55.855 Untitled[39469:707] /reading.php?another=value&special_number=42&

You can use something like:
NSString *parameter1 = #"blah";
NSString *parameter2 = #"anotherblah";
NSString *fullURL = [NSString stringWithFormat:#"/reading.php?title=%#&image_url=%#", parameter1, parameter2];
You can add as many parameters as you want. Use "%#" where you will be dynamically adding the text.
Good luck :)

Copy pasting from Paul.s - which is the correct answer, imo - and fixing a (most likely inconsequential) problem of a dangling ampersand...
#interface NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
#end
#implementation NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
{
if (!self.count) return #"";
NSMutableString *params = [NSMutableString string];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
[params appendFormat:#"%#=%#&", key, obj];
}];
// return everything except that last ampersand
return [[params copy] substringToIndex:[params length]-1];
}
#end

Related

Sort array with a count value

I have an array which contains some strings. For each character of a string an integer value is assigned. For example a=2,b=5,c=6 ,o=1,k=3 etc
The final value in the a string is the sum of the character's value. So that for an example string "BOOK" the string will be stored as "BOOK (7)". Similarly every string will have a final integer value. I would like to sort these array with these final integer values stored in the string which is present in each array index. The array contains more than 200,000 words. So the sorting process should be pretty fast. Is there any method for it?
A brutal quick example could be, if your strings structure is always the same, like "Book (7)" you can operate on the string by finding the number between the "()" and then you can use a dictionary to store temporally the objects:
NSMutableArray *arr=[NSMutableArray arrayWithObjects:#"Book (99)",#"Pencil (66)",#"Trash (04)", nil];
NSLog(#"%#",arr);
NSMutableDictionary *dict=[NSMutableDictionary dictionary];
//Find the numbers and store each element in the dictionary
for (int i =0;i<arr.count;i++) {
NSString *s=[arr objectAtIndex:i];
int start=[s rangeOfString:#"("].location;
NSString *sub1=[s substringFromIndex:start];
NSString *temp1=[sub1 stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *newIndex=[temp1 stringByReplacingOccurrencesOfString:#")" withString:#""];
//NSLog(#"%d",[newIndex intValue]);
[dict setValue:s forKey:newIndex];
}
//Sorting the keys and create the new array
NSArray *sortedValues = [[dict allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSMutableArray *newArray=[[NSMutableArray alloc]init];
for(NSString *valor in sortedValues){
[newArray addObject:[dict valueForKey:valor]];
}
NSLog(#"%#",newArray);
This prints:
(
"Book (99)",
"Pencil (66)",
"Trash (04)"
)
(
"Trash (04)",
"Pencil (66)",
"Book (99)"
)
as i understand, you want to sort an array which contains string formated in the following
a=3
and you want to sort according to the number while ignoring the character.
in this case the following code will work with you
-(NSArray *)Sort:(NSArray*)myArray
{
return [myArray sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2)
{
NSString *first = [[obj1 componentsSeparatedByString:#"="] objectAtIndex:1];
NSString *second = [[obj2 componentsSeparatedByString:#"="] objectAtIndex:1];
return [first caseInsensitiveCompare:second];
}];
}
How to use it:
NSArray *arr= [[NSArray alloc] initWithObjects:#"a=3",#"b=1",#"c=4",#"f=2", nil];
NSArray *sorted = [self Sort:arr];
for (NSString* str in sorted)
{
NSLog(#"%#",str);
}
Output
b=1
f=2
a=3
c=4
Try this methods
+(NSString*)strTotalCount:(NSString*)str
{
NSInteger totalCount = 0;
// initial your character-count directory
NSDictionary* characterDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:2], [NSString stringWithUTF8String:"a"],
[NSNumber numberWithInt:5], [NSString stringWithUTF8String:"b"],
[NSNumber numberWithInt:6], [NSString stringWithUTF8String:"c"],
[NSNumber numberWithInt:1], [NSString stringWithUTF8String:"o"],
[NSNumber numberWithInt:3], [NSString stringWithUTF8String:"k"],
nil];
NSString* tempString = str;
for (NSInteger i =0; i<tempString.length; i++) {
NSString* character = [tempString substringWithRange:NSMakeRange(i, 1)];
character = [character lowercaseString];
NSNumber* count = [characterDictionary objectForKey:character];
totalCount += [count integerValue];
};
return [NSString stringWithFormat:#"%#(%d)",str,totalCount];
}
The test sentence:
NSLog(#"%#", [ViewController strTotalCount:#"BOOK"]);
will output " BOOK(10) "
You may change the ViewController to you own class name;
First - create a custom object to save your values. Don't put the value inside the string.
Sorting is not your base problem. The problem is that you are saving values into a string from where they are difficult to extract.
#interface StringWithValue
#property (nonatomic, copy, readwrite) NSString* text;
#property (nonatomic, assign, readwrite) NSUInteger value;
- (id)initWithText:(NSString*)text;
- (NSComparisonResult)compare:(StringWithValue*)anotherString;
#end
#implementation StringWithValue
#synthesize text = _text;
#synthesize value = _value;
- (id)initWithText:(NSString*)text {
self = [super init];
if (!self) {
return nil;
}
self.text = text;
self.value = [self calculateValueForText:text];
return self;
}
- (NSComparisonResult)compare:(StringWithValue*)anotherString {
if (self.value anotherString.value) {
return NSOrderedDescending;
}
else {
return NSOrderedSame;
}
}
- (NSString*)description {
return [NSString stringWithFormat:#"%# (%u)", self.text, self.value];
}
#end
Sorting the array then would be a simple use of sortUsingSelector:.
Note this will beat all other answers in performance as there is no need to parse the value with every comparison.

How do i remove a substring from an nsstring?

Ok, say I have the string "hello my name is donald"
Now, I want to remove everything from "hello" to "is"
The thing is, "my name" could be anything, it could also be "his son"
So basically, simply doing stringByReplacingOccurrencesOfString won't work.
(I do have RegexLite)
How would I do this?
Use like below it will help you
NSString *hello = #"his is name is isName";
NSRange rangeSpace = [hello rangeOfString:#" "
options:NSBackwardsSearch];
NSRange isRange = [hello rangeOfString:#"is"
options:NSBackwardsSearch
range:NSMakeRange(0, rangeSpace.location)];
NSString *finalResult = [NSString stringWithFormat:#"%# %#",[hello substringToIndex:[hello rangeOfString:#" "].location],[hello substringFromIndex:isRange.location]];
NSLog(#"finalResult----%#",finalResult);
The following NSString Category may help you. It works good for me but not created by me. Thanks for the author.
NSString+Whitespace.h
#import <Foundation/Foundation.h>
#interface NSString (Whitespace)
- (NSString *)stringByCompressingWhitespaceTo:(NSString *)seperator;
#end
NSString+Whitespace.m
#
import "NSString+Whitespace.h"
#implementation NSString (Whitespace)
- (NSString *)stringByCompressingWhitespaceTo:(NSString *)seperator
{
//NSArray *comps = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *comps = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSMutableArray *nonemptyComps = [[NSMutableArray alloc] init];
// only copy non-empty entries
for (NSString *oneComp in comps)
{
if (![oneComp isEqualToString:#""])
{
[nonemptyComps addObject:oneComp];
}
}
return [nonemptyComps componentsJoinedByString:seperator]; // already marked as autoreleased
}
#end
If you always know your string will begin with 'hello my name is ', then that is 17 characters, including the final space, so if you
NSString * hello = "hello my name is Donald Trump";
NSString * finalNameOnly = [hello substringFromIndex:17];

iPhone: can i use NSString search in NSArray

can i use like this r not
for (NSString *string in userInfo){
lblUserName.text = (NSString *) [userInfo objectForKey:#"name"];
lblLocation.text = (NSString *) [userInfo objectForKey:#"location"];
lblDescription.text =(NSString *) [userInfo objectForKey:#"description"];
NSLog(#"User profileData Received: %#", userInfo);
}
here userInfo = NSArray (this is delegate i can change )
lblUserName = label name
ObectForKey is using for searching NSString
thank you, is this Right r wrong one
if not how i have to work out
NSArray are not key based but index based. Use NSDictionary instead or use index to retrieve items.
and I don't understand what is the loop for, you don't even use the string var in it ???

Parse NSDictionary to a string with custom separators

I have an NSMutableDictionary with some values in it, and I need to join the keys and values into a string, so
> name = Fred
> password = cakeismyfavoritefood
> email = myemailaddress#is.short
becomes name=Fred&password=cakeismyfavoritefood&email=myemailaddress#is.short
How can I do this? Is there a way to join NSDictionaries into strings?
You can easily do that enumerating dictionary keys and objects:
NSMutableString *resultString = [NSMutableString string];
for (NSString* key in [yourDictionary allKeys]){
if ([resultString length]>0)
[resultString appendString:#"&"];
[resultString appendFormat:#"%#=%#", key, [yourDict objectForKey:key]];
}
Quite same question as Turning a NSDictionary into a string using blocks?
NSMutableArray* parametersArray = [[NSMutableArray alloc] init];
[yourDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[parametersArray addObject:[NSString stringWithFormat:#"%#=%#", key, obj]];
}];
NSString* parameterString = [parametersArray componentsJoinedByString:#"&"];
[parametersArray release];

Turning a NSDictionary into a string using blocks?

I'm sure there is a way to do this using blocks, but I cant figure it out. I want to to turn an NSDictionary into url-style string of parameters.
If I have an NSDictionary which looks like this:
dict = [NSDictionary dictionaryWithObjectsAndKeys:#"blue", #"color", #"large", #"size", nil]];
Then how would I turn that into a string that looks like this:
"color=blue&size=large"
EDIT
Thanks for the clues below. This should do it:
NSMutableString *parameterString;
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[parameterString appendFormat:#"%#=%#&", key, obj];
}];
parameterString = [parameterString substringToIndex:[string length] - 1];
Quite same solution but without the substring:
NSMutableArray* parametersArray = [[[NSMutableArray alloc] init] autorelease];
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[parametersArray addObject:[NSString stringWithFormat:#"%#=%#", key, obj]];
}];
NSString* parameterString = [parametersArray componentsJoinedByString:#"&"];
Create a mutable string, then iterate the dictionary getting each key. Look up the value for that key, and add the key=value& to the string. When you finish that loop, remove the last &.
I presume this is going to be fed through a URL, you will also want to have some method that encodes your strings, in case they contain items like & or +, etc.
NSMutableString* yourString = #"";
for (id key in dict) {
[yourString appendFormat:#"%#=%#&", key, ((NSString*)[dict objectForKey:key])];
}
NSRange r;
r.location = 0;
r.size = [yourString length]-1;
[yourString deleteCharactersInRange:r];