简体   繁体   中英

Can I copy from NSString to NSMutableString?

I have strValue as NSString , and I'd like to copy strValue 's content to another place.

The place is mstrValue , which is an NSMutableString . Space for mstrValue has already been allocated.

I wonder how can I use memcpy or strcpy for this purpose.

If it is impossible, I'd like to know other ways to do it.

Your question isn't too clear but if you want to set the mutable string's value to the other string then do this:

[mstrValue setString:strValue];

If you want to append the value then do this:

[mstrValue appendString:strValue];

Both of these assume that at some point you did:

mstrValue = [[NSMutableString alloc] init];

Have a look at the docs for NSMutableString . There are lots of methods for updating its value.

I'll always prefer to used [NSString stringWithFormat@"%@", strValue]; because then you clearly get a new autoreleased string and can dispose of string "strValue" correctly.

NSMutableString *mstrValue = [NSMutableString stringWithFormat:@"%@", strValue];

OR

NSMutableString *mstrValue = [NSMutableString stringWithString:strValue];

除非要正确处理字符串编码,否则应避免使用memcpy或strcpy。

Yes with object allocation:

NSMutableString *mstrValue = [[NSMutableString alloc] initWithString:strValue];

You can do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM