Objective-C中的快捷键连接nsstring。

时间:2022-02-09 00:20:18

Are there any shortcuts to (stringByAppendingString:) string concatenation in Objective-C, or shortcuts for working with NSString in general?

在Objective-C中有什么快捷方式(stringByAppendingString:)字符串连接吗?或者一般使用NSString的快捷方式?

For example, I'd like to make:

例如,我想说:

NSString *myString = @"This";
NSString *test = [myString stringByAppendingString:@" is just a test"];

something more like:

更多的东西:

string myString = "This";
string test = myString + " is just a test";

30 个解决方案

#1


577  

Two answers I can think of... neither is particularly as pleasant as just having a concatenation operator.

我能想到两个答案……这两种方法都不像具有连接操作符那样令人愉快。

First, use an NSMutableString, which has an appendString method, removing some of the need for extra temp strings.

首先,使用一个NSMutableString,它有一个appendString方法,可以删除一些额外临时字符串的需要。

Second, use an NSArray to concatenate via the componentsJoinedByString method.

其次,使用NSArray通过componentsJoinedByString方法连接。

#2


1047  

An option:

[NSString stringWithFormat:@"%@/%@/%@", one, two, three];

Another option:

I'm guessing you're not happy with multiple appends (a+b+c+d), in which case you could do:

我猜你对多重附加(a+b+c+d)不满意,在这种情况下你可以这样做:

NSLog(@"%@", [Util append:one, @" ", two, nil]); // "one two"
NSLog(@"%@", [Util append:three, @"/", two, @"/", one, nil]); // three/two/one

using something like

使用类似

+ (NSString *) append:(id) first, ...
{
    NSString * result = @"";
    id eachArg;
    va_list alist;
    if(first)
    {
        result = [result stringByAppendingString:first];
        va_start(alist, first);
        while (eachArg = va_arg(alist, id)) 
        result = [result stringByAppendingString:eachArg];
        va_end(alist);
    }
    return result;
}

#3


139  

If you have 2 NSString literals, you can also just do this:

如果你有两个NSString文字,你也可以这样做:

NSString *joinedFromLiterals = @"ONE " @"MILLION " @"YEARS " @"DUNGEON!!!";

That's also useful for joining #defines:

这对加入#定义也很有用:

#define STRINGA @"Also, I don't know "
#define STRINGB @"where food comes from."
#define JOINED STRINGA STRINGB

Enjoy.

享受。

#4


66  

I keep returning to this post and always end up sorting through the answers to find this simple solution that works with as many variables as needed:

我一直回到这篇文章,最后总是整理出答案来找到这个简单的解决方案,它能满足需要的很多变量:

[NSString stringWithFormat:@"%@/%@/%@", three, two, one];

For example:

例如:

NSString *urlForHttpGet = [NSString stringWithFormat:@"http://example.com/login/username/%@/userid/%i", userName, userId];

#5


43  

Well, as colon is kind of special symbol, but is part of method signature, it is possible to exted the NSString with category to add this non-idiomatic style of string concatenation:

嗯,因为冒号是一种特殊的符号,但它是方法签名的一部分,可以将NSString添加到类中来添加这种非惯用的字符串连接方式:

[@"This " : @"feels " : @"almost like " : @"concatenation with operators"];

You can define as many colon separated arguments as you find useful... ;-)

您可以定义许多冒号分隔的参数,如您发现有用的…:-)

For a good measure, I've also added concat: with variable arguments that takes nil terminated list of strings.

对于一个好的度量,我还添加了concat:带有变量参数,它以nil终止字符串列表。

//  NSString+Concatenation.h

#import <Foundation/Foundation.h>

@interface NSString (Concatenation)

- (NSString *):(NSString *)a;
- (NSString *):(NSString *)a :(NSString *)b;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d;

- (NSString *)concat:(NSString *)strings, ...;

@end

//  NSString+Concatenation.m

#import "NSString+Concatenation.h"

@implementation NSString (Concatenation)

- (NSString *):(NSString *)a { return [self stringByAppendingString:a];}
- (NSString *):(NSString *)a :(NSString *)b { return [[self:a]:b];}
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c
    { return [[[self:a]:b]:c]; }
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d
    { return [[[[self:a]:b]:c]:d];}

- (NSString *)concat:(NSString *)strings, ...
{
    va_list args;
    va_start(args, strings);

    NSString *s;    
    NSString *con = [self stringByAppendingString:strings];

    while((s = va_arg(args, NSString *))) 
        con = [con stringByAppendingString:s];

    va_end(args);
    return con;
}
@end

//  NSString+ConcatenationTest.h

#import <SenTestingKit/SenTestingKit.h>
#import "NSString+Concatenation.h"

@interface NSString_ConcatenationTest : SenTestCase

@end

//  NSString+ConcatenationTest.m

#import "NSString+ConcatenationTest.h"

@implementation NSString_ConcatenationTest

- (void)testSimpleConcatenation 
{
    STAssertEqualObjects([@"a":@"b"], @"ab", nil);
    STAssertEqualObjects([@"a":@"b":@"c"], @"abc", nil);
    STAssertEqualObjects([@"a":@"b":@"c":@"d"], @"abcd", nil);
    STAssertEqualObjects([@"a":@"b":@"c":@"d":@"e"], @"abcde", nil);
    STAssertEqualObjects([@"this " : @"is " : @"string " : @"concatenation"],
     @"this is string concatenation", nil);
}

- (void)testVarArgConcatenation 
{
    NSString *concatenation = [@"a" concat:@"b", nil];
    STAssertEqualObjects(concatenation, @"ab", nil);

    concatenation = [concatenation concat:@"c", @"d", concatenation, nil];
    STAssertEqualObjects(concatenation, @"abcdab", nil);
}

#6


33  

create a method......

创建一个方法……

- (NSString *)strCat: (NSString *)one: (NSString *)two
{
    NSString *myString;
    myString = [NSString stringWithFormat:@"%@%@", one , two];
    return myString;
}

Then, in whatever function you need it in, set your string or textfield or whatever to the return value of this function.

然后,在你需要的任何函数中,设置你的字符串或textfield或者其他函数的返回值。

Or what you can do to make a shortcut is convert the NSString into a c++ string and use the '+' there.

或者你可以做的是把NSString转换成一个c++字符串,然后使用“+”。

Hope this helps!!!!!

希望这有助于! ! ! ! !

#7


30  

Use this way:

使用这个方法:

NSString *string1, *string2, *result;

string1 = @"This is ";
string2 = @"my string.";

result = [result stringByAppendingString:string1];
result = [result stringByAppendingString:string2];

OR

result = [result stringByAppendingString:@"This is "];
result = [result stringByAppendingString:@"my string."];

#8


29  

Macro:

宏:

// stringConcat(...)
//     A shortcut for concatenating strings (or objects' string representations).
//     Input: Any number of non-nil NSObjects.
//     Output: All arguments concatenated together into a single NSString.

#define stringConcat(...) \
    [@[__VA_ARGS__] componentsJoinedByString:@""]

Test Cases:

测试用例:

- (void)testStringConcat {
    NSString *actual;

    actual = stringConcat(); //might not make sense, but it's still a valid expression.
    STAssertEqualObjects(@"", actual, @"stringConcat");

    actual = stringConcat(@"A");
    STAssertEqualObjects(@"A", actual, @"stringConcat");

    actual = stringConcat(@"A", @"B");
    STAssertEqualObjects(@"AB", actual, @"stringConcat");

    actual = stringConcat(@"A", @"B", @"C");
    STAssertEqualObjects(@"ABC", actual, @"stringConcat");

    // works on all NSObjects (not just strings):
    actual = stringConcat(@1, @" ", @2, @" ", @3);
    STAssertEqualObjects(@"1 2 3", actual, @"stringConcat");
}

Alternate macro: (if you wanted to enforce a minimum number of arguments)

替代宏(如果您想执行最少数量的参数)

// stringConcat(...)
//     A shortcut for concatenating strings (or objects' string representations).
//     Input: Two or more non-nil NSObjects.
//     Output: All arguments concatenated together into a single NSString.

#define stringConcat(str1, str2, ...) \
    [@[ str1, str2, ##__VA_ARGS__] componentsJoinedByString:@""];

#9


27  

When building requests for web services, I find doing something like the following is very easy and makes concatenation readable in Xcode:

在构建web服务的请求时,我发现执行以下操作非常简单,并且在Xcode中使连接可读:

NSString* postBody = {
    @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    @"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
    @" <soap:Body>"
    @"  <WebServiceMethod xmlns=\"\">"
    @"   <parameter>test</parameter>"
    @"  </WebServiceMethod>"
    @" </soap:Body>"
    @"</soap:Envelope>"
};

#10


24  

Shortcut by creating AppendString (AS) macro ...

创建AppendString (AS)宏的快捷方式…

#define AS(A,B)    [(A) stringByAppendingString:(B)]
NSString *myString = @"This"; NSString *test = AS(myString,@" is just a test");

Note:

注意:

If using a macro, of course just do it with variadic arguments, see EthanB's answer.

如果使用宏,当然要用变量参数来做,看看乙烷的答案。

#11


13  

NSString *label1 = @"Process Name: ";
NSString *label2 = @"Process Id: ";
NSString *processName = [[NSProcessInfo processInfo] processName];
NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
NSString *testConcat = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];

#12


9  

Here's a simple way, using the new array literal syntax:

这里有一个简单的方法,使用新的数组文字语法:

NSString * s = [@[@"one ", @"two ", @"three"] componentsJoinedByString:@""];
                  ^^^^^^^ create array ^^^^^
                                               ^^^^^^^ concatenate ^^^^^

#13


8  

The only way to make c = [a stringByAppendingString: b] any shorter is to use autocomplete at around the st point. The + operator is part of C, which doesn't know about Objective-C objects.

使c = [stringByAppendingString: b]的惟一方法是在st点附近使用自动完成。+运算符是C的一部分,它不知道Objective-C对象。

#14


8  

How about shortening stringByAppendingString and use a #define:

如何缩短stringByAppendingString并使用#define:

#define and stringByAppendingString

Thus you would use:

因此可以使用:

NSString* myString = [@"Hello " and @"world"];

Problem is that it only works for two strings, you're required to wrap additional brackets for more appends:

问题是,它只适用于两个字符串,您需要将附加的括号括起来,以获得更多的附加条件:

NSString* myString = [[@"Hello" and: @" world"] and: @" again"];

#15


8  

NSString *myString = @"This";
NSString *test = [myString stringByAppendingString:@" is just a test"];

After a couple of years now with Objective C I think this is the best way to work with Objective C to achieve what you are trying to achieve.

几年后,我认为这是与Objective C合作的最好方法,以实现你想要达到的目标。

Start keying in "N" in your Xcode application and it autocompletes to "NSString". key in "str" and it autocompletes to "stringByAppendingString". So the keystrokes are quite limited.

在Xcode应用程序中开始键入“N”,然后自动完成“NSString”。键入“str”,并自动完成“stringByAppendingString”。所以击键是非常有限的。

Once you get the hang of hitting the "@" key and tabbing the process of writing readable code no longer becomes a problem. It is just a matter of adapting.

一旦你掌握了点击“@”键的窍门,并且把编写可读代码的过程写下来,就不再是一个问题了。这只是一个适应的问题。

#16


7  

NSString *label1 = @"Process Name: ";
NSString *label2 = @"Process Id: ";
NSString *processName = [[NSProcessInfo processInfo] processName];
NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
NSString *testConcat = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];

#17


7  

NSString *result=[NSString stringWithFormat:@"%@ %@", @"Hello", @"World"];

#18


6  

Was trying the following in the lldb pane

在lldb窗格中尝试下列操作吗?

[NSString stringWithFormat:@"%@/%@/%@", three, two, one];

which errors.

这错误。

instead use alloc and initWithFormat method:

改为使用alloc和initWithFormat方法:

[[NSString alloc] initWithFormat:@"%@/%@/%@", @"three", @"two", @"one"];

#19


5  

I tried this code. it's worked for me.

我试着这段代码。它为我工作。

NSMutableString * myString=[[NSMutableString alloc]init];
myString=[myString stringByAppendingString:@"first value"];
myString=[myString stringByAppendingString:@"second string"];

#20


4  

This is for better logging, and logging only - based on dicius excellent multiple argument method. I define a Logger class, and call it like so:

这是为了更好的日志记录和日志记录——基于dicius优秀的多参数方法。我定义了一个Logger类,并将其命名为:

[Logger log: @"foobar ", @" asdads ", theString, nil];

Almost good, except having to end the var args with "nil" but I suppose there's no way around that in Objective-C.

几乎是好的,除了必须用“nil”结束var args,但我想在Objective-C中没有办法。

Logger.h

Logger.h

@interface Logger : NSObject {
}
+ (void) log: (id) first, ...;
@end

Logger.m

Logger.m

@implementation Logger

+ (void) log: (id) first, ...
{
    // TODO: make efficient; handle arguments other than strings
    // thanks to @diciu http://*.com/questions/510269/how-do-i-concatenate-strings-in-objective-c
    NSString * result = @"";
    id eachArg;
    va_list alist;
    if(first)
    {
        result = [result stringByAppendingString:first];
        va_start(alist, first);
        while (eachArg = va_arg(alist, id)) 
        {
            result = [result stringByAppendingString:eachArg];
        }
        va_end(alist);
    }
    NSLog(@"%@", result);
}

@end 

In order to only concat strings, I'd define a Category on NSString and add a static (+) concatenate method to it that looks exactly like the log method above except it returns the string. It's on NSString because it's a string method, and it's static because you want to create a new string from 1-N strings, not call it on any one of the strings that are part of the append.

为了只使用concat字符串,我将在NSString上定义一个类别,并添加一个静态的(+)连接方法,它看起来与上面的日志方法完全一样,只是它返回了字符串。它是在NSString上的,因为它是一个字符串方法,它是静态的,因为你想要从1-N字符串创建一个新的字符串,而不是在附加的任何一个字符串上调用它。

#21


4  

NSNumber *lat = [NSNumber numberWithDouble:destinationMapView.camera.target.latitude];
NSNumber *lon = [NSNumber numberWithDouble:destinationMapView.camera.target.longitude];
NSString *DesconCatenated = [NSString stringWithFormat:@"%@|%@",lat,lon];

#22


3  

Try stringWithFormat:

试试stringWithFormat:

NSString *myString = [NSString stringWithFormat:@"%@ %@ %@ %d", "The", "Answer", "Is", 42];

#23


3  

When dealing with strings often I find it easier to make the source file ObjC++, then I can concatenate std::strings using the second method shown in the question.

在处理字符串时,我常常发现使源文件ObjC++更容易,然后我可以使用问题中显示的第二个方法连接std::strings。

std::string stdstr = [nsstr UTF8String];

//easier to read and more portable string manipulation goes here...

NSString* nsstr = [NSString stringWithUTF8String:stdstr.c_str()];

#24


3  

My preferred method is this:

我的首选方法是:

NSString *firstString = @"foo";
NSString *secondString = @"bar";
NSString *thirdString = @"baz";

NSString *joinedString = [@[firstString, secondString, thirdString] join];

You can achieve it by adding the join method to NSArray with a category:

您可以通过将join方法添加到NSArray中来实现它:

#import "NSArray+Join.h"
@implementation NSArray (Join)
-(NSString *)join
{
    return [self componentsJoinedByString:@""];
}
@end

@[] it's the short definition for NSArray, I think this is the fastest method to concatenate strings.

@[]这是NSArray的简短定义,我认为这是连接字符串的最快方法。

If you don't want to use the category, use directly the componentsJoinedByString: method:

如果您不想使用类别,则直接使用componentsJoinedByString:方法:

NSString *joinedString = [@[firstString, secondString, thirdString] componentsJoinedByString:@""];

#25


3  

You can use NSArray as

你可以用NSArray。

NSString *string1=@"This"

NSString *string2=@"is just"

NSString *string3=@"a test"  

NSArray *myStrings = [[NSArray alloc] initWithObjects:string1, string2, string3,nil];

NSString *fullLengthString = [myStrings componentsJoinedByString:@" "];

or

you can use

您可以使用

NSString *imageFullName=[NSString stringWithFormat:@"%@ %@ %@.", string1,string2,string3];

#26


1  

Either of these formats work in XCode7 when I tested:

当我测试时,这些格式都在XCode7中工作:

NSString *sTest1 = {@"This" " and that" " and one more"};
NSString *sTest2 = {
  @"This"
  " and that"
  " and one more"
};

NSLog(@"\n%@\n\n%@",sTest1,sTest2);

For some reason, you only need the @ operator character on the first string of the mix.

出于某些原因,您只需要在混合的第一个字符串中使用@运算符。

However, it doesn't work with variable insertion. For that, you can use this extremely simple solution with the exception of using a macro on "cat" instead of "and".

但是,它不使用变量插入。为此,您可以使用这个非常简单的解决方案,但只使用“cat”而不是“and”的宏。

#27


0  

listOfCatalogIDs =[@[@"id[]=",listOfCatalogIDs] componentsJoinedByString:@""];

#28


0  

Let's imagine that u don't know how many strings there.

假设u不知道有多少根弦。

NSMutableArray *arrForStrings = [[NSMutableArray alloc] init];
for (int i=0; i<[allMyStrings count]; i++) {
    NSString *str = [allMyStrings objectAtIndex:i];
    [arrForStrings addObject:str];
}
NSString *readyString = [[arrForStrings mutableCopy] componentsJoinedByString:@", "];

#29


0  

For all Objective C lovers that need this in a UI-Test:

对于所有在ui测试中需要这个的目标C爱好者:

-(void) clearTextField:(XCUIElement*) textField{

    NSString* currentInput = (NSString*) textField.value;
    NSMutableString* deleteString = [NSMutableString new];

    for(int i = 0; i < currentInput.length; ++i) {
        [deleteString appendString: [NSString stringWithFormat:@"%c", 8]];
    }
    [textField typeText:deleteString];
}

#30


-1  

In Swift

在斯威夫特

let str1 = "This"
let str2 = "is just a test"

var appendStr1 = "\(str1) \(str2)" // appendStr1 would be "This is just a test"
var appendStr2 = str1 + str2 // // appendStr2 would be "This is just a test"

Also, you can use += operator for the same as below...

同样,您可以使用+=操作符,如下所示…

var str3 = "Some String" 
str3 += str2            // str3 would be "Some String is just a test"

#1


577  

Two answers I can think of... neither is particularly as pleasant as just having a concatenation operator.

我能想到两个答案……这两种方法都不像具有连接操作符那样令人愉快。

First, use an NSMutableString, which has an appendString method, removing some of the need for extra temp strings.

首先,使用一个NSMutableString,它有一个appendString方法,可以删除一些额外临时字符串的需要。

Second, use an NSArray to concatenate via the componentsJoinedByString method.

其次,使用NSArray通过componentsJoinedByString方法连接。

#2


1047  

An option:

[NSString stringWithFormat:@"%@/%@/%@", one, two, three];

Another option:

I'm guessing you're not happy with multiple appends (a+b+c+d), in which case you could do:

我猜你对多重附加(a+b+c+d)不满意,在这种情况下你可以这样做:

NSLog(@"%@", [Util append:one, @" ", two, nil]); // "one two"
NSLog(@"%@", [Util append:three, @"/", two, @"/", one, nil]); // three/two/one

using something like

使用类似

+ (NSString *) append:(id) first, ...
{
    NSString * result = @"";
    id eachArg;
    va_list alist;
    if(first)
    {
        result = [result stringByAppendingString:first];
        va_start(alist, first);
        while (eachArg = va_arg(alist, id)) 
        result = [result stringByAppendingString:eachArg];
        va_end(alist);
    }
    return result;
}

#3


139  

If you have 2 NSString literals, you can also just do this:

如果你有两个NSString文字,你也可以这样做:

NSString *joinedFromLiterals = @"ONE " @"MILLION " @"YEARS " @"DUNGEON!!!";

That's also useful for joining #defines:

这对加入#定义也很有用:

#define STRINGA @"Also, I don't know "
#define STRINGB @"where food comes from."
#define JOINED STRINGA STRINGB

Enjoy.

享受。

#4


66  

I keep returning to this post and always end up sorting through the answers to find this simple solution that works with as many variables as needed:

我一直回到这篇文章,最后总是整理出答案来找到这个简单的解决方案,它能满足需要的很多变量:

[NSString stringWithFormat:@"%@/%@/%@", three, two, one];

For example:

例如:

NSString *urlForHttpGet = [NSString stringWithFormat:@"http://example.com/login/username/%@/userid/%i", userName, userId];

#5


43  

Well, as colon is kind of special symbol, but is part of method signature, it is possible to exted the NSString with category to add this non-idiomatic style of string concatenation:

嗯,因为冒号是一种特殊的符号,但它是方法签名的一部分,可以将NSString添加到类中来添加这种非惯用的字符串连接方式:

[@"This " : @"feels " : @"almost like " : @"concatenation with operators"];

You can define as many colon separated arguments as you find useful... ;-)

您可以定义许多冒号分隔的参数,如您发现有用的…:-)

For a good measure, I've also added concat: with variable arguments that takes nil terminated list of strings.

对于一个好的度量,我还添加了concat:带有变量参数,它以nil终止字符串列表。

//  NSString+Concatenation.h

#import <Foundation/Foundation.h>

@interface NSString (Concatenation)

- (NSString *):(NSString *)a;
- (NSString *):(NSString *)a :(NSString *)b;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d;

- (NSString *)concat:(NSString *)strings, ...;

@end

//  NSString+Concatenation.m

#import "NSString+Concatenation.h"

@implementation NSString (Concatenation)

- (NSString *):(NSString *)a { return [self stringByAppendingString:a];}
- (NSString *):(NSString *)a :(NSString *)b { return [[self:a]:b];}
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c
    { return [[[self:a]:b]:c]; }
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d
    { return [[[[self:a]:b]:c]:d];}

- (NSString *)concat:(NSString *)strings, ...
{
    va_list args;
    va_start(args, strings);

    NSString *s;    
    NSString *con = [self stringByAppendingString:strings];

    while((s = va_arg(args, NSString *))) 
        con = [con stringByAppendingString:s];

    va_end(args);
    return con;
}
@end

//  NSString+ConcatenationTest.h

#import <SenTestingKit/SenTestingKit.h>
#import "NSString+Concatenation.h"

@interface NSString_ConcatenationTest : SenTestCase

@end

//  NSString+ConcatenationTest.m

#import "NSString+ConcatenationTest.h"

@implementation NSString_ConcatenationTest

- (void)testSimpleConcatenation 
{
    STAssertEqualObjects([@"a":@"b"], @"ab", nil);
    STAssertEqualObjects([@"a":@"b":@"c"], @"abc", nil);
    STAssertEqualObjects([@"a":@"b":@"c":@"d"], @"abcd", nil);
    STAssertEqualObjects([@"a":@"b":@"c":@"d":@"e"], @"abcde", nil);
    STAssertEqualObjects([@"this " : @"is " : @"string " : @"concatenation"],
     @"this is string concatenation", nil);
}

- (void)testVarArgConcatenation 
{
    NSString *concatenation = [@"a" concat:@"b", nil];
    STAssertEqualObjects(concatenation, @"ab", nil);

    concatenation = [concatenation concat:@"c", @"d", concatenation, nil];
    STAssertEqualObjects(concatenation, @"abcdab", nil);
}

#6


33  

create a method......

创建一个方法……

- (NSString *)strCat: (NSString *)one: (NSString *)two
{
    NSString *myString;
    myString = [NSString stringWithFormat:@"%@%@", one , two];
    return myString;
}

Then, in whatever function you need it in, set your string or textfield or whatever to the return value of this function.

然后,在你需要的任何函数中,设置你的字符串或textfield或者其他函数的返回值。

Or what you can do to make a shortcut is convert the NSString into a c++ string and use the '+' there.

或者你可以做的是把NSString转换成一个c++字符串,然后使用“+”。

Hope this helps!!!!!

希望这有助于! ! ! ! !

#7


30  

Use this way:

使用这个方法:

NSString *string1, *string2, *result;

string1 = @"This is ";
string2 = @"my string.";

result = [result stringByAppendingString:string1];
result = [result stringByAppendingString:string2];

OR

result = [result stringByAppendingString:@"This is "];
result = [result stringByAppendingString:@"my string."];

#8


29  

Macro:

宏:

// stringConcat(...)
//     A shortcut for concatenating strings (or objects' string representations).
//     Input: Any number of non-nil NSObjects.
//     Output: All arguments concatenated together into a single NSString.

#define stringConcat(...) \
    [@[__VA_ARGS__] componentsJoinedByString:@""]

Test Cases:

测试用例:

- (void)testStringConcat {
    NSString *actual;

    actual = stringConcat(); //might not make sense, but it's still a valid expression.
    STAssertEqualObjects(@"", actual, @"stringConcat");

    actual = stringConcat(@"A");
    STAssertEqualObjects(@"A", actual, @"stringConcat");

    actual = stringConcat(@"A", @"B");
    STAssertEqualObjects(@"AB", actual, @"stringConcat");

    actual = stringConcat(@"A", @"B", @"C");
    STAssertEqualObjects(@"ABC", actual, @"stringConcat");

    // works on all NSObjects (not just strings):
    actual = stringConcat(@1, @" ", @2, @" ", @3);
    STAssertEqualObjects(@"1 2 3", actual, @"stringConcat");
}

Alternate macro: (if you wanted to enforce a minimum number of arguments)

替代宏(如果您想执行最少数量的参数)

// stringConcat(...)
//     A shortcut for concatenating strings (or objects' string representations).
//     Input: Two or more non-nil NSObjects.
//     Output: All arguments concatenated together into a single NSString.

#define stringConcat(str1, str2, ...) \
    [@[ str1, str2, ##__VA_ARGS__] componentsJoinedByString:@""];

#9


27  

When building requests for web services, I find doing something like the following is very easy and makes concatenation readable in Xcode:

在构建web服务的请求时,我发现执行以下操作非常简单,并且在Xcode中使连接可读:

NSString* postBody = {
    @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    @"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
    @" <soap:Body>"
    @"  <WebServiceMethod xmlns=\"\">"
    @"   <parameter>test</parameter>"
    @"  </WebServiceMethod>"
    @" </soap:Body>"
    @"</soap:Envelope>"
};

#10


24  

Shortcut by creating AppendString (AS) macro ...

创建AppendString (AS)宏的快捷方式…

#define AS(A,B)    [(A) stringByAppendingString:(B)]
NSString *myString = @"This"; NSString *test = AS(myString,@" is just a test");

Note:

注意:

If using a macro, of course just do it with variadic arguments, see EthanB's answer.

如果使用宏,当然要用变量参数来做,看看乙烷的答案。

#11


13  

NSString *label1 = @"Process Name: ";
NSString *label2 = @"Process Id: ";
NSString *processName = [[NSProcessInfo processInfo] processName];
NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
NSString *testConcat = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];

#12


9  

Here's a simple way, using the new array literal syntax:

这里有一个简单的方法,使用新的数组文字语法:

NSString * s = [@[@"one ", @"two ", @"three"] componentsJoinedByString:@""];
                  ^^^^^^^ create array ^^^^^
                                               ^^^^^^^ concatenate ^^^^^

#13


8  

The only way to make c = [a stringByAppendingString: b] any shorter is to use autocomplete at around the st point. The + operator is part of C, which doesn't know about Objective-C objects.

使c = [stringByAppendingString: b]的惟一方法是在st点附近使用自动完成。+运算符是C的一部分,它不知道Objective-C对象。

#14


8  

How about shortening stringByAppendingString and use a #define:

如何缩短stringByAppendingString并使用#define:

#define and stringByAppendingString

Thus you would use:

因此可以使用:

NSString* myString = [@"Hello " and @"world"];

Problem is that it only works for two strings, you're required to wrap additional brackets for more appends:

问题是,它只适用于两个字符串,您需要将附加的括号括起来,以获得更多的附加条件:

NSString* myString = [[@"Hello" and: @" world"] and: @" again"];

#15


8  

NSString *myString = @"This";
NSString *test = [myString stringByAppendingString:@" is just a test"];

After a couple of years now with Objective C I think this is the best way to work with Objective C to achieve what you are trying to achieve.

几年后,我认为这是与Objective C合作的最好方法,以实现你想要达到的目标。

Start keying in "N" in your Xcode application and it autocompletes to "NSString". key in "str" and it autocompletes to "stringByAppendingString". So the keystrokes are quite limited.

在Xcode应用程序中开始键入“N”,然后自动完成“NSString”。键入“str”,并自动完成“stringByAppendingString”。所以击键是非常有限的。

Once you get the hang of hitting the "@" key and tabbing the process of writing readable code no longer becomes a problem. It is just a matter of adapting.

一旦你掌握了点击“@”键的窍门,并且把编写可读代码的过程写下来,就不再是一个问题了。这只是一个适应的问题。

#16


7  

NSString *label1 = @"Process Name: ";
NSString *label2 = @"Process Id: ";
NSString *processName = [[NSProcessInfo processInfo] processName];
NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
NSString *testConcat = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];

#17


7  

NSString *result=[NSString stringWithFormat:@"%@ %@", @"Hello", @"World"];

#18


6  

Was trying the following in the lldb pane

在lldb窗格中尝试下列操作吗?

[NSString stringWithFormat:@"%@/%@/%@", three, two, one];

which errors.

这错误。

instead use alloc and initWithFormat method:

改为使用alloc和initWithFormat方法:

[[NSString alloc] initWithFormat:@"%@/%@/%@", @"three", @"two", @"one"];

#19


5  

I tried this code. it's worked for me.

我试着这段代码。它为我工作。

NSMutableString * myString=[[NSMutableString alloc]init];
myString=[myString stringByAppendingString:@"first value"];
myString=[myString stringByAppendingString:@"second string"];

#20


4  

This is for better logging, and logging only - based on dicius excellent multiple argument method. I define a Logger class, and call it like so:

这是为了更好的日志记录和日志记录——基于dicius优秀的多参数方法。我定义了一个Logger类,并将其命名为:

[Logger log: @"foobar ", @" asdads ", theString, nil];

Almost good, except having to end the var args with "nil" but I suppose there's no way around that in Objective-C.

几乎是好的,除了必须用“nil”结束var args,但我想在Objective-C中没有办法。

Logger.h

Logger.h

@interface Logger : NSObject {
}
+ (void) log: (id) first, ...;
@end

Logger.m

Logger.m

@implementation Logger

+ (void) log: (id) first, ...
{
    // TODO: make efficient; handle arguments other than strings
    // thanks to @diciu http://*.com/questions/510269/how-do-i-concatenate-strings-in-objective-c
    NSString * result = @"";
    id eachArg;
    va_list alist;
    if(first)
    {
        result = [result stringByAppendingString:first];
        va_start(alist, first);
        while (eachArg = va_arg(alist, id)) 
        {
            result = [result stringByAppendingString:eachArg];
        }
        va_end(alist);
    }
    NSLog(@"%@", result);
}

@end 

In order to only concat strings, I'd define a Category on NSString and add a static (+) concatenate method to it that looks exactly like the log method above except it returns the string. It's on NSString because it's a string method, and it's static because you want to create a new string from 1-N strings, not call it on any one of the strings that are part of the append.

为了只使用concat字符串,我将在NSString上定义一个类别,并添加一个静态的(+)连接方法,它看起来与上面的日志方法完全一样,只是它返回了字符串。它是在NSString上的,因为它是一个字符串方法,它是静态的,因为你想要从1-N字符串创建一个新的字符串,而不是在附加的任何一个字符串上调用它。

#21


4  

NSNumber *lat = [NSNumber numberWithDouble:destinationMapView.camera.target.latitude];
NSNumber *lon = [NSNumber numberWithDouble:destinationMapView.camera.target.longitude];
NSString *DesconCatenated = [NSString stringWithFormat:@"%@|%@",lat,lon];

#22


3  

Try stringWithFormat:

试试stringWithFormat:

NSString *myString = [NSString stringWithFormat:@"%@ %@ %@ %d", "The", "Answer", "Is", 42];

#23


3  

When dealing with strings often I find it easier to make the source file ObjC++, then I can concatenate std::strings using the second method shown in the question.

在处理字符串时,我常常发现使源文件ObjC++更容易,然后我可以使用问题中显示的第二个方法连接std::strings。

std::string stdstr = [nsstr UTF8String];

//easier to read and more portable string manipulation goes here...

NSString* nsstr = [NSString stringWithUTF8String:stdstr.c_str()];

#24


3  

My preferred method is this:

我的首选方法是:

NSString *firstString = @"foo";
NSString *secondString = @"bar";
NSString *thirdString = @"baz";

NSString *joinedString = [@[firstString, secondString, thirdString] join];

You can achieve it by adding the join method to NSArray with a category:

您可以通过将join方法添加到NSArray中来实现它:

#import "NSArray+Join.h"
@implementation NSArray (Join)
-(NSString *)join
{
    return [self componentsJoinedByString:@""];
}
@end

@[] it's the short definition for NSArray, I think this is the fastest method to concatenate strings.

@[]这是NSArray的简短定义,我认为这是连接字符串的最快方法。

If you don't want to use the category, use directly the componentsJoinedByString: method:

如果您不想使用类别,则直接使用componentsJoinedByString:方法:

NSString *joinedString = [@[firstString, secondString, thirdString] componentsJoinedByString:@""];

#25


3  

You can use NSArray as

你可以用NSArray。

NSString *string1=@"This"

NSString *string2=@"is just"

NSString *string3=@"a test"  

NSArray *myStrings = [[NSArray alloc] initWithObjects:string1, string2, string3,nil];

NSString *fullLengthString = [myStrings componentsJoinedByString:@" "];

or

you can use

您可以使用

NSString *imageFullName=[NSString stringWithFormat:@"%@ %@ %@.", string1,string2,string3];

#26


1  

Either of these formats work in XCode7 when I tested:

当我测试时,这些格式都在XCode7中工作:

NSString *sTest1 = {@"This" " and that" " and one more"};
NSString *sTest2 = {
  @"This"
  " and that"
  " and one more"
};

NSLog(@"\n%@\n\n%@",sTest1,sTest2);

For some reason, you only need the @ operator character on the first string of the mix.

出于某些原因,您只需要在混合的第一个字符串中使用@运算符。

However, it doesn't work with variable insertion. For that, you can use this extremely simple solution with the exception of using a macro on "cat" instead of "and".

但是,它不使用变量插入。为此,您可以使用这个非常简单的解决方案,但只使用“cat”而不是“and”的宏。

#27


0  

listOfCatalogIDs =[@[@"id[]=",listOfCatalogIDs] componentsJoinedByString:@""];

#28


0  

Let's imagine that u don't know how many strings there.

假设u不知道有多少根弦。

NSMutableArray *arrForStrings = [[NSMutableArray alloc] init];
for (int i=0; i<[allMyStrings count]; i++) {
    NSString *str = [allMyStrings objectAtIndex:i];
    [arrForStrings addObject:str];
}
NSString *readyString = [[arrForStrings mutableCopy] componentsJoinedByString:@", "];

#29


0  

For all Objective C lovers that need this in a UI-Test:

对于所有在ui测试中需要这个的目标C爱好者:

-(void) clearTextField:(XCUIElement*) textField{

    NSString* currentInput = (NSString*) textField.value;
    NSMutableString* deleteString = [NSMutableString new];

    for(int i = 0; i < currentInput.length; ++i) {
        [deleteString appendString: [NSString stringWithFormat:@"%c", 8]];
    }
    [textField typeText:deleteString];
}

#30


-1  

In Swift

在斯威夫特

let str1 = "This"
let str2 = "is just a test"

var appendStr1 = "\(str1) \(str2)" // appendStr1 would be "This is just a test"
var appendStr2 = str1 + str2 // // appendStr2 would be "This is just a test"

Also, you can use += operator for the same as below...

同样,您可以使用+=操作符,如下所示…

var str3 = "Some String" 
str3 += str2            // str3 would be "Some String is just a test"