Get a string with ascii code objective-c - objective-c

I have a ascii code, for the letter 'a', and I want to get a string by its ascii code, is it possible with NSString?

This could also work:
NSString *foo = [NSString stringWithFormat:#"%c", 97];
Didn’t test it.

If you mean you have a byte that represents an ASCII-encoded character and you want to make a string out of it, NSString has an initializer just for that.
char characterCodeInASCII = 97;
NSString *stringWithAInIt = [[NSString alloc] initWithBytes:&characterCodeInASCII length:1 encoding:NSASCIIStringEncoding];

Related

Comparing strings is giving false in Objective-C

I am comparing two strings using isEqual method and it is giving NO.
if ([trie.name isEqual:string]) {
isFound = YES;
break;
}
The trie.name is a string initialized using [[NSString alloc] initWithCharacters:&uchar length:ucharLen], where uchar is a unichar. The string is a constant string #"N". I have checked the hash values and both differ. I am not sure why creating a string using different initializer gives different hash for the same string value. In this case, how to check for string equality?
Please see the attached screenshot of the debug variables.
Currently, I am using the code:
NSString *string = #"Pirates";
unichar uchar = [string characterAtIndex:0];
size_t ucharLen = sizeof(uchar);
NSString *str = [[NSString alloc] initWithCharacters:&uchar length:ucharLen];
XCTAssertTrue([str isEqual:#"P"]);
If I given the length: as 1, it works properly. How to get the length of the unichar. Will it always be 1 so that I can hardcode 1 in this case?
The problem is with:
unichar uchar = [string characterAtIndex:0];
size_t ucharLen = sizeof(uchar);
NSString *str = [[NSString alloc] initWithCharacters:&uchar length:ucharLen];
You are creating a string from a single unichar which means the length needs to be 1. But the sizeof(unichar) returns 2 since unichar is a 16-bit (2-byte) value so you end up telling the string you are passing 2 characters, not 1.
So the resulting string contains two characters - the one you actually want and a second, random bit of garbage that happens to be at that memory address.
Just hardcode 1:
unichar uchar = [string characterAtIndex:0];
NSString *str = [[NSString alloc] initWithCharacters:&uchar length:1];

Format string that already has format specifier %#

I have a string which already contains a formatter %#.
NSString *str = #"This is an %#";
I need to parse that string and to replace %# with 'example'. If I use
[NSString stringWithFormat:#"%#", str];
I get the following output:
This is an %#
I want output like:
This is an example
NSString *str = #"This is an %#";
str = [str stringByReplacingOccurrencesOfString:#"%#" withString:#"example"];
I would recommand to use the formatted string as "format"
NSString *str = #"This is an %#";
str = [NSString stringWithFormat:str, #"example"];
is working with every type. A better solution than replacing, because you can use unspecified replacings
is very usefull if you use localized.strings with x values you want to add ;)

NSString stringByReplacingPercentEscapesUsingEncoding doesn't work

I need to get url string from NSString. I do the following:
NSString * str = [NSString stringWithString:#"i#gmail.com"];
NSString * eStr = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#",eStr);
The result is i#gmail.com. But I need i%40gmail.com. replacing NSUTF8StringEncoding with NSASCIIStringEncoding doesn't help.
You're using the wrong method. This does the opposite, translating percent
escapes to their characters. You probably want to use
stringByAddingPercentEscapesUsingEncoding:.
NSString *str = #"i#gmail.com";
NSString *eStr =
[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Apart from that, looks like the # character is not escaped by default. Then,
as the documentation for the above method points out, you'll need to use
CoreFoundation to achieve what you want.
NSString *str = #"i#gmail.com";
CFStringRef eStr = CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(CFStringRef)str,
NULL,
(CFStringRef)#"#",
kCFStringEncodingUTF8
);
NSLog(#"%#", eStr);
CFRelease(eStr);
Please check the documentation to know more about the function used and
how to make it fit your needs.

Change value of mutable string

How to change value of mutable string ? Here is what I do
NSString *str = #"This is string";
NSMutableString *str = [NSMutableString stringWithFormat:#"%#", str];
str = #"New string" -> wrong incompatible pointer types assigning to NSMutableString from NSString
You only need to use NSMutableString if you want to change parts of the string in place (append, insert etc.), often for performance reasons.
If you want to assign new values to the string variable, you're fine with a good old NSString as your last line simple assigns a complete new string object to str:
You can use setString to replace the whole string:
NSString *str = #"This is string";
NSMutableString *mutableStr = [NSMutableString stringWithFormat:#"%#", str];
...
[mutableStr setString:#"a different non mutable string"];
As indicated in another answer, a non-mutable NSString may be enough for your purposes.
This is how you should initialize a NSMutableString:
NSMutableString *string = [[NSMutableString alloc]init];
You could use any other way specified in the docs. The way you are doing it, you are not creating any instance of the NSMutableString class. Then, if you want to add some string to it:
[string appendString:#"content"];

Merge 5 NSStrings in Objective-C

I have multiple NSStrings and i wish to merge them into one other, here is my code so far...
NSString *newURL = [_parameters objectForKey:#"url"];
NSString *emailBody = #"Hey!<br>I just snipped my long url with My Cool App for iPhone in just a few seconds!<p><b>"+newURL+#"</b></p>";
If you know the number of your existing strings, you can just concat them:
NSString* longString = [firstString stringByAppendingString:secondString];
or:
NSString* longString = [NSString stringWithFormat:#"A string: %#, a float: %1.2f", #"string", 31415.9265];
If you have an arbitrary number of strings, you could put them in an NSArray and join them with:
NSArray* chunks = ... get an array, say by splitting it;
NSString* string = [chunks componentsJoinedByString: #" :-) "];
(Taken from http://borkware.com/quickies/one?topic=NSString)
Another good resource for string handling in Cocoa is: "String Programming Guide"
You can try
NSString *emailBody = [ NSString stringWithFormat: #"Hey!<br>I just snipped my long url with Snippety Snip for iPhone in just a few seconds, why not check it out?<p><b>%#</b></p>", newURL ];
Given that you've got multiple strings I recommend using an Array:
NSArray *array = [NSArray arrayWithObjects:#"URL", #"person", "body"];
NSString *combined = [array componentsJoinedByString:#""];
Formatting string has better readability and less error-prone:
NSString *newURL = [_parameters objectForKey:#"url"];
NSString *emailBody = [NSString stringWithFormat:#"Hey!<br>I just snipped my long url with Snippety Snip for iPhone in just a few seconds, why not check it out?<p><b>%#</b></p>", newUrl, newUrl];
You can concatenate strings in Cocoa using:
[NSString stringByAppendingString:]
Or you could use the [NSString stringWithFormat] method which will allow you to specify a C-style format string with a variable argument list to populate the escape sequences.