52

文字列内に文字列を配置したい。基本的に擬似コードで:

"first part of string" + "(varying string)" + "third part of string"

Objective-Cでこれを行うにはどうすればよいですか? obj-c で簡単に連結する方法はありますか? ありがとう!

4

7 に答える 7

121

はい、します

NSString *str = [NSString stringWithFormat: @"first part %@ second part", varyingString];

連結には、使用できますstringByAppendingString

NSString *str = @"hello ";
str = [str stringByAppendingString:@"world"]; //str is now "hello world"

複数の文字列の場合

NSString *varyingString1 = @"hello";
NSString *varyingString2 = @"world";
NSString *str = [NSString stringWithFormat: @"%@ %@", varyingString1, varyingString2];
//str is now "hello world"
于 2012-08-15T15:11:12.430 に答える
13

テーマのバリエーション:

NSString *varying = @"whatever it is";
NSString *final = [NSString stringWithFormat:@"first part %@ third part", varying];

NSString *varying = @"whatever it is";
NSString *final = [[@"first part" stringByAppendingString:varying] stringByAppendingString:@"second part"];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendFormat:@"%@ third part", varying];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendString:varying];
[final appendString:@"third part"];
于 2012-08-15T15:11:52.200 に答える
10
NSString * varyingString = ...;
NSString * cat = [NSString stringWithFormat:@"%s%@%@",
  "first part of string",
  varyingString,
  @"third part of string"];

または単に-[NSString stringByAppendingString:]

于 2012-08-15T15:11:39.530 に答える
6

通常は-stringWithFormatここを使用します。

NSString *myString = [NSString stringWithFormat:@"%@%@%@", @"some text", stringVariable, @"some more text"];
于 2012-08-15T15:11:11.853 に答える
3

やるだけ

NSString* newString=[NSString stringWithFormat:@"first part of string (%@) third part of string", @"foo"];

これにより、

@"first part of string (foo) third part of string"
于 2012-08-15T15:11:46.333 に答える
1

簡単なもの:

[[@"first" stringByAppendingString:@"second"] stringByAppendingString:@"third"];

連結する文字列が多い場合は、NSMutableStringパフォーマンスを向上させるために使用する必要があります

于 2012-08-15T16:08:56.703 に答える