Append variables to string in Objective-C [duplicate] - objective-c

How can I combine "stringURL" and "stringSearch" together?
- (IBAction)search:(id)sender;{
stringURL = #"http://www.websitehere.com/index.php?s=";
stringSearch = search.text;
/* Something such as:
stringURL_ = stringURL + stringSearch */
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:stringURL_]]];
}

Philippe gave a good example.
You can also use plain stringWithFormat: method.
NSString *combined = [NSString stringWithFormat:#"%#%#", stringURL, stringSearch];
This way you can manipulate string even more by putting somethig inbetween the strings like:
NSString *combined = [NSString stringWithFormat:#"%#/someMethod.php?%#", stringURL, stringSearch];

NSString* combinedString = [stringUrl stringByAppendingString: search.text];

NSString * combined = [stringURL stringByAppendingString:stringSearch];

Instead of stringByAppendingString:, you could also use
NSString *combined = [NSString stringWithFormat: #"%#%#",
stringURL, stringSearch];
This is especially interesting/convenient if you have more than one string to append. Otherwise, the stringbyAppendingString: method is probably the better choice.

You can use stringByAppendingString:
stringURL = [#"http://www.websitehere.com/index.php?s="
stringByAppendingString:search.text];

If you want to have some control about the format of the parameter you should assemble
your URL string with
[NSString stringWithFormat:#"http://www.websitehere.com/index.php?s=%#", search.text]
This solution is charming because you can append almost anything which can be inserted into a printf-style format.

I would not have given the answer of such general question.
There are many answers of same type question have already given. First find the answer of your question from existing question.
NSString* myURLString = [NSString stringWithFormat:#"http://www.websitehere.com/index.php?s=%#", search.text];

Related

I am getting garbage values while running this code in Xcode using objective c

- (IBAction)btndlr:(id)sender
{
NSString *str =txtdata.text;
lblfinal.text=[NSString stringWithFormat:#"%d/60",(int)str];
}
After running this code without any errors i get garbage value as output in the label.any guidance will be appreciated.thank you.
You must use the NSString method intValue to make it work, try this:
- (IBAction)btndlr:(id)sender
{
NSString *str = txtdata.text;
lblfinal.text = [NSString stringWithFormat:#"%d/60",[str intValue]];
}
EDIT:
If you want to perform the calculation before writing it out, you should change the last line to:
lblfinal.text = [NSString stringWithFormat:#"%d",[str intValue]/60];
And by the way, if you use division you might want a decimal number as output, then you can write:
lblfinal.text = [NSString stringWithFormat:#"%.2f",[str floatValue]/60];
Hope it helped!
You can't do computations inside format strings. You have to convert the string to an integer with e.g. the intValue property, and perform the computation outside:
- (IBAction)btndlr:(id)sender
{
NSString *str = txtdata.text;
lblfinal.text = [NSString stringWithFormat:#"%d", str.intValue / 60];
}
Please try this one
- (IBAction)btndlr:(id)sender
{
NSString *str = txtdata.text;
lblfinal.text = [NSString stringWithFormat:#"%d",[str intValue]/60];
}

Objective-C URL encoding issues

I am creating a URL string like so:
[Items appendString:[object objectForKey:#"Items"]];
[Items appendString:#"*"];
[Items deleteCharactersInRange:NSMakeRange([Items length]-1, 1)];
//This returns this: ~SEWER/FLATWORK SUPPLY & INSTALL - 25% of CONTRACT*~SEWER/FLATWORK SUPPLY & INSTALL - 75% of CONTRACT*SUMP PUMP PIT
//add Items to URL
NSString *fullURL = [NSString stringWithFormat:#"https://example.com?Items=%#, [Items stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
but it returns like so:
Items=~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2025%25%20of%20CONTRACT*~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2075%25%20of%20CONTRACT*SUMP%20PUMP%20PIT
how do I get it return like this:
%20%26%20 instead of %20&%20 for the & ?
I think the issue is that the method tries to be too clever - it only does as much as is necessary to get a legal URL and because you don't have a question mark in your string, it probably thinks it is OK to leave the ampersands in.
Try constructing the whole URL and do the escaping on the whole URL.
NSString *fullURL = [[#"https://example.com?Items=" stringByAppendingString: items]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Or perhaps use stringByAddingPercentEncodingWithAllowedCharacters:.
Try this.
fullURL=[fullURL stringByReplacingOccurrencesOfString:#"&" withString:#"%26"];
NSLog(#"fullURL: %# ...", fullURL);
Use CFURLCreateStringByAddingPercentEscapes() for getting UTF8stringencoding of characters
NSString *urlString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef) Items, NULL, CFSTR("!*'();:#&=+$,/?%#[]"), kCFStringEncodingUTF8))

stringByAppendingFormat not working

I have an NSString and fail to apply the following statement:
NSString *myString = #"some text";
[myString stringByAppendingFormat:#"some text = %d", 3];
no log or error, the string just doesn't get changed. I already tried with NSString (as documented) and NSMutableString.
any clues most welcome.
I would suggest correcting to (documentation):
NSString *myString = #"some text";
myString = [myString stringByAppendingFormat:#" = %d", 3];
From the docs:
Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments.
It's working, you're just ignoring the return value, which is the string with the appended format. (See the docs.) You can't modify an NSString — to modify an NSMutableString, use -appendFormat: instead.
Of course, in your toy example, you could shorten it to this:
NSString *myString = [NSString stringWithFormat:#"some text = %d", 3];
However, it's likely that you need to append a format string to an existing string created elsewhere. In that case, and particularly if you're appending multiple parts, it's good to think about and balance the pros and cons of using a mutable string or several immutable, autoreleased strings.
Creating strings with #"" always results in immutable strings. If you want to create a new NSMutableString do it as following.
NSMutableString *myString = [NSMutableString stringWithString:#"some text"];
[myString appendFormat:#"some text = %d", 3];
I had a similar warning message while appending a localized string. This is how I resolved it
NSString *msgBody = [msgBody stringByAppendingFormat:#"%#",NSLocalizedString(#"LOCALSTRINGMSG",#"Message Body")];

How to remove first 3 characters from NSString?

I have a string like this "A. rahul VyAs"
and i want to remove "A. " and the space after the "A." so that new string would be "rahul VyAs"
How do i achieve this?
You can use the NSString instance methods substringWithRange: or substringFromIndex:
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringWithRange:NSMakeRange(3, [str length]-3)];
or
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringFromIndex:3];
This is a solution I have seen specifically for removing regularly occurring prefixes and solving the answer to the question How do I remove "A. "?
NSString * name = #"A. rahul VyAs";
NSString * prefixToRemove = #"A. ";
name = [name stringByReplacingOccurrencesOfString:prefixToRemove withString:#""];
This code will remove what you tell it to remove/change if the character set exists, such as "A. ", even if the three characters (or more/less) are in the middle of the string.
If you wanted to remove rahul, you can. It's diverse in that you specify exactly what you want removed or changed, and if it exists anywhere in the String, it will be removed or changed.
If you only want a certain specified number of characters removed from the front of the text that are always random or unknown, use the [string length] method as is the top answer.
If you want to remove or change certain characters that repeatedly appear, the method I have used will enable that, similar to Wordsearch on document editors.
Try this,
char *string=[#"A. rahul VyAs" cStringUsingEncoding:NSUTF8StringEncoding];
char *subString=&name[3];
NSString *newString=[NSString stringWithCString:subString encoding:NSUTF8StringEncoding];
It's this simple:
myString = [myString subStringFromIndex:3]
That's it.

How to add percent sign to NSString

I want to have a percentage sign in my string after a digit. Something like this: 75%.
How can I have this done? I tried:
[NSString stringWithFormat:#"%d\%", someDigit];
But it didn't work for me.
The code for percent sign in NSString format is %%. This is also true for NSLog() and printf() formats.
The escape code for a percent sign is "%%", so your code would look like this
[NSString stringWithFormat:#"%d%%", someDigit];
Also, all the other format specifiers can be found at Conceptual Strings Articles
If that helps in some cases, it is possible to use the unicode character:
NSLog(#"Test percentage \uFF05");
The accepted answer doesn't work for UILocalNotification. For some reason, %%%% (4 percent signs) or the unicode character '\uFF05' only work for this.
So to recap, when formatting your string you may use %%. However, if your string is part of a UILocalNotification, use %%%% or \uFF05.
seems if %% followed with a %#, the NSString will go to some strange codes
try this and this worked for me
NSString *str = [NSString stringWithFormat:#"%#%#%#", #"%%",
[textfield text], #"%%"];
uese following code.
NSString *searchText = #"Bhupi"
NSString *formatedSearchText = [NSString stringWithFormat:#"%%%#%%",searchText];
will output: %Bhupi%
iOS 9.2.1, Xcode 7.2.1, ARC enabled
You can always append the '%' by itself without any other format specifiers in the string you are appending, like so...
int test = 10;
NSString *stringTest = [NSString stringWithFormat:#"%d", test];
stringTest = [stringTest stringByAppendingString:#"%"];
NSLog(#"%#", stringTest);
For iOS7.0+
To expand the answer to other characters that might cause you conflict you may choose to use:
- (NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters
Written out step by step it looks like this:
int test = 10;
NSString *stringTest = [NSString stringWithFormat:#"%d", test];
stringTest = [[stringTest stringByAppendingString:#"%"]
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]];
stringTest = [stringTest stringByRemovingPercentEncoding];
NSLog(#"percent value of test: %#", stringTest);
Or short hand:
NSLog(#"percent value of test: %#", [[[[NSString stringWithFormat:#"%d", test]
stringByAppendingString:#"%"] stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]] stringByRemovingPercentEncoding]);
Thanks to all the original contributors. Hope this helps. Cheers!