How to concatenate two strings on iPhone?

后端 未结 6 1170
既然无缘
既然无缘 2021-02-02 17:27

How to connect string \"Hello\" and string \"World\" to \"HelloWorld\"? Looks like \"+\" doesn\'t work.

相关标签:
6条回答
  • 2021-02-02 18:07

    How about:

    NSString *hello = @"Hello";
    NSString *world = @"World";
    NSString *helloWorld = [hello stringByAppendingString:world];
    
    0 讨论(0)
  • 2021-02-02 18:08

    Bill, I like yout simple solution and I'd like to note that you can also eliminate the space between the two NSStrings:

    NSString * myString = @"Hello"@"World";
    
    0 讨论(0)
  • 2021-02-02 18:09
    NSString *string = [NSString stringWithFormat:@"%@%@", @"Hello", @"World"];
    NSLog(@"%@", string);
    

    That should do the trick, although I am sure there is a better way to do this, just out of memory. I also must say this is untested so forgive me. Best thing is to find the stringWithFormat documentation for NSString.

    0 讨论(0)
  • 2021-02-02 18:12

    If you have two literal strings, you can simply code:

    NSString * myString = @"Hello" @"World";
    

    This is a useful technique to break up long literal strings within your code.

    However, this will not work with string variables, where you'd want to use stringWithFormat: or stringByAppendingString:, as mentioned in the other responses.

    0 讨论(0)
  • 2021-02-02 18:12

    there's always NSMutableString..

    NSMutableString *myString = [NSMutableString stringWithString:@"Hello"];
    [myString appendString: @"World"];
    

    Note:

    NSMutableString *myString = @"Hello"; // won't work, literal strings aren't mutable
    
    0 讨论(0)
  • 2021-02-02 18:23
    t3.text=[t1.text stringByAppendingString:t2.text];
    
    0 讨论(0)
提交回复
热议问题