Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate char and string on iPhone?

I want to add some marks to separate some strings. How to add a char to a string?

e.g. add '\x01' to "Hello", add '\x02' before "World" and add '\x03' after "World".

So I can create a string "\x01 Hello \x02 World \x03" which has some separate marks.

like image 562
Chilly Zhong Avatar asked Mar 02 '09 12:03

Chilly Zhong


People also ask

Can I concatenate string with char?

The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function.

How do you concatenate characters?

Use the ampersand & character instead of the CONCATENATE function. The ampersand (&) calculation operator lets you join text items without having to use a function. For example, =A1 & B1 returns the same value as =CONCATENATE(A1,B1).

Can we concatenate string and char in Java?

How do you concatenate characters in java? Concatenating strings would only require a + between the strings, but concatenating chars using + will change the value of the char into ascii and hence giving a numerical output.


2 Answers

Hm..

You could do something like this:

NSString *hello = @"hello";
char ch [] = {'\x01'};
hello = [hello stringByAppendingString:[NSString stringWithUTF8String:(char*)ch]];

I make a a char* to append out of your single char and use stringWithUTF8String to add it.

There's probably a less long-winded way of solving it however!

Nick.

like image 24
Nick Cartwright Avatar answered Sep 21 '22 08:09

Nick Cartwright


If you want to modify a string, you have to use NSMutableString instead of NSString. There is no such need if you want to create a string from scratch.

For instance, you may want to use +stringWithFormat: method:

NSString * myString = [NSString stringWithFormat:@"%c %@ %c %@ %c",
                                                 0x01,
                                                 @"Hello",
                                                 0x02,
                                                 @"World",
                                                 0x03];
like image 192
mouviciel Avatar answered Sep 20 '22 08:09

mouviciel