Trying to append const char *str to a NSSting *:
In .h
#interface SomeViewController : UIViewController
{
NSString *consoleText;
}
#property (nonatomic, retain) NSString *consoleText;
#end
In .mm
#synthesize consoleText;
The following is OK:
const char *str = "abc";
self.consoleText = [NSString stringWithFormat: #"%#%#", self.consoleText, [NSString stringWithUTF8String:str]];
but the following failed:
self.consoleText = [self.consoleText stringByAppendingString:[NSString stringWithUTF8String:str]];
Why stringByAppendingString fails but stringWithFormat works? Thanks!
In two of the operations you are doing different things one is appending existing string and another you are setting a new string
To append string there should be a string object
self.consoleText = [self.consoleText stringByAppendingString:[NSString stringWithUTF8String:str]];
As per understanding self.consoleText ---> nil so it will not appending string.
so do something like
if(self.consoleText)
{
self.consoleText = [self.consoleText stringByAppendingString:[NSString stringWithUTF8String:str]];
}else
{
self.consoleText = [NSString stringWithUTF8String:str];
}
NSString *original = #"Thinking";
const char *str = "...";
NSString *other = [NSString stringWithCString:str encoding:NSASCIIStringEncoding];
original = [original stringByAppendingString:other];
NSLog(#"original: %#", original); // original: Thinking...
Related
I am getting UTF-8 (hex): Hc3b8rt back from a server instead of the string "Hørt".
I need to convert this response to regular UTF-8.
What I have tried:
NSString *string = [dict objectForKey:#"suggest"];
const char *cfilename=[string UTF8String];
NSString *str = [NSString stringWithUTF8String:cfilename];
Thank you for your time!
There's no way you can decode this. As #JoachimIsaksson stated in the comments above, how can you tell if "abba" is exactly "abba" or two unicode chars?
use string encoding, NSISOLatin1StringEncoding
- (id)initWithCString:(const char *)nullTerminatedCString
encoding:(NSStringEncoding)encoding
Or shortly,
NSString *str = [NSString stringWithCString:cfilename
encoding:NSISOLatin1StringEncoding];
Edit after comments:
This is kind of strange. I have done some experiments after your comments and found some strange behaviour.
- (void) testStringEncodingOK {
NSString *string = #"h\u00c3\u00a5r";
const char *cfilename=[string cStringUsingEncoding:NSISOLatin1StringEncoding];
NSString *cs = [NSString stringWithUTF8String:cfilename];
NSLog(#"String: %#", cs);
}
This output: hår
But if you get the \U in capital, not \u, then I replaced them to \u. And then it did not work. Seem the ,
- (void) testStringEncodingConfused {
NSString *string = #"h\\U00c3\\U00a5r";
string = [string stringByReplacingOccurrencesOfString:#"\\U" withString:#"\\u"];
NSLog(#"Original string:%#", string); // now string = #"h\u00c3\u00a5r"
const char *cfilename=[string cStringUsingEncoding:NSISOLatin1StringEncoding];
NSString *cs = [NSString stringWithUTF8String:cfilename];
NSLog(#"String: %#", cs);
}
The output is, h\u00c3\u00a5r
Use below code..
const char *ch = [yourstring cStringUsingEncoding:NSISOLatin1StringEncoding];
yourstring = [[NSString alloc]initWithCString:ch encoding:NSUTF8StringEncoding];
NSLog(#"%#",yourstring);
let me know it is working or not...
Happy Coding....
use this code
NSString *string = [dict objectForKey:#"suggest"];
const char *cfilename=[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *str = [NSString stringWithUTF8String:cfilename];
and tell if it is working or not.
I have an iPhone application in which i am creating an array in the didfinishlaunch in the appdelegate. Like this:
for(int i=1;i<53;i++)
{
NSString *namestring=[NSString stringWithString:#"avatar"];
NSString *string = [NSString stringWithFormat:#"%d",i];
NSString *pngstring=[NSString stringWithString:#".png"];
string = [string stringByAppendingString:pngstring];
namestring = [namestring stringByAppendingString:string];
NSLog(#"%#",namestring);
[avtararray addObject:namestring];
}
working fine.and everywhere i am doing the avatar job with my avatararray in the appdelegate.But in one case when i pop back to the previous view and try to load the string from the array again
NSString *avatarstringt=[[appDelegate.avtararray objectAtIndex:i]description];here it is crashing with a an error
-[CFString description]: message sent to deallocated instance..
when doing the profile job i know that the leak is in the above loop in the appendingstring code.Can anybody help me to remove this?
First of all, Never do this
NSString *string = [NSString stringWithFormat:#"%d",i];
NSString *pngstring=[NSString stringWithString:#".png"];
string = [string stringByAppendingString:pngstring];
The following statements, are redundant
NSString *namestring=[NSString stringWithString:#"avatar"];
NSString *pngstring=[NSString stringWithString:#".png"];
and should be written as:
NSString *namestring=#"avatar";
NSString *pngstring=#".png";
You can use as :
NSString *namestring=#"avatar";
NSString *numberString = [NSString stringWithFormat:#"%d",i];
NSString *pngstring=#"png";
namestring = [namestring stringByAppendingFormat:#"%#.%#",numberString,pngstring];
Even the shortest of code :
for(NSInteger i=1;i<5;i++){
NSString *namestring = [NSString stringWithFormat:#"avatar%#.png",#(i)];
NSLog(#"%#",namestring);
}
As suggested by rmaddy: you can use i as integer, no need of converting it into nsnumber
NSString *namestring = [NSString stringWithFormat:#"avatar%d.png",i];
I'm new to iPhone development, I want to convert a string to hex format.
For example 00A400024F01 to 0x00,0xA4,0x00,0x02,0x4F,0x01 I guess I should start by dividing the string and then convert the grouped value. I don't know how to do that.
u just found answer from this stackoverflow question:-
How to convert an NSString to hex values
+ (NSString *) stringToHex:(NSString *)str
{
NSUInteger len = [str length];
unichar *chars = malloc(len * sizeof(unichar));
[str getCharacters:chars];
NSMutableString *hexString = [[NSMutableString alloc] init];
for(NSUInteger i = 0; i < len; i++ )
{
// [hexString [NSString stringWithFormat:#"%02x", chars[i]]]; /*previous input*/
[hexString appendFormat:#"%02x", chars[i]]; /*EDITED PER COMMENT BELOW*/
}
free(chars);
return [hexString autorelease];
}
UPDATE
You can divide one sting on to two string using below method:-
NSString * mystring = #"Hello,How are you";// suppos your string like that
NSArray * array = [mystring componentsSeparatedByString:#","];
NSString * str1 = [array objectAtIndex:0]; //Hello
NSString * str2 = [array objectAtIndex:1]; //How are you
and if you want to murge two string in to one string like :-
NSString *str1=#"hi Sweet Lady";
NSString *str2=#"How are you";
NSString *mainstr=[NSString stringWithFormat:#"%# %#",str1,str2];
Output is ==== hi Sweet Lady How are you
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];
I have an NSString that gets assigned a string value. How do I take this NSString and insert #"-thumbnail" between the file's name and its extension?
In other words, how do I go from:
NSString *fileName = #"myFile.png";
to:
NSString *thumbnailName = [NSString someMagicFunction...]
NSLog(#"%#", thumbnailName); // Should Output "myFile-thumbnail.png"
The NSString additions for path components can come in handy, specifically: pathExtension and stringByDeletingPathExtension
Edit: see also: stringByAppendingPathExtension: (as pointed out by Dave DeLong)
NSString * ext = [fileName pathExtension];
NSString * baseName = [fileName stringByDeletingPathExtension];
NSString * thumbBase = [baseName stringByAppendingString:#"-thumbnail"];
NSString * thumbnailName = [thumbBase stringByAppendingPathExtension:ext];
If you really want that magicFunction to exist, you can add a category method to NSString like so:
#interface NSString (MoreMagic)
- (NSString *)stringByAddingFileSuffix:(NSString *)suffix;
#end
#implementation NSString (MoreMagic)
- (NSString *)stringByAddingFileSuffix:(NSString *)suffix
{
NSString * extension = [self pathExtension];
NSString * baseName = [self stringByDeletingPathExtension];
NSString * thumbBase = [baseName stringByAppendingString:suffix];
return [thumbBase stringByAppendingPathExtension:extension];
}
#end
To be used as follows:
NSString * thumbnailName = [fileName stringByAddingFileSuffix:#"-thumbnail"];
If you are certain of your filenames, you could also simply do:
[NSString stringByReplacingOccurrencesOfString:#"." withString:#"-thumbnail."]
But the path handling stuff is cleaner (doesn't care how many "." you have in the name) and good to know about for trickier cases.
We've got an opensource category for just that: -[NSString ks_stringWithPathSuffix:]