Objective-C 中连接 NSString 的快捷方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/510269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:07:06  来源:igfitidea点击:

Shortcuts in Objective-C to concatenate NSStrings

objective-cnsstringstring-concatenation

提问by typeoneerror

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

stringByAppendingString:在 Objective-C 中是否有 ( ) 字符串连接的快捷方式,或者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";

采纳答案by Chris Blackwell

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

我能想到的两个答案......都不像只有一个串联运算符那么令人愉快。

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

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

Second, use an NSArrayto concatenate via the componentsJoinedByStringmethod.

其次,使用 anNSArray通过componentsJoinedByString方法进行连接。

回答by diciu

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;
}

回答by Johannes Fahrenkrug

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

如果您有 2 个 NSString文字,您也可以这样做:

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

That's also useful for joining #defines:

这对于加入#defines 也很有用:

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

Enjoy.

享受。

回答by Kyle Clegg

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];

回答by Sidd Menon

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 text field or whatever to the return value of this function.

然后,在您需要它的任何函数中,将字符串或文本字段或任何内容设置为该函数的返回值。

Or, to make a shortcut, convert the NSString into a C++ string and use the '+' there.

或者,要创建快捷方式,请将 NSString 转换为 C++ 字符串并在那里使用“+”。

回答by Palimondo

Well, as colon is kind of special symbol, but ispart of method signature, it is possible to exted the NSStringwith category to add this non-idiomaticstyle 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 nilterminated 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);
}

回答by Taimur Ajmal

Use stringByAppendingString:this way:

使用stringByAppendingString:这种方式:

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."];

回答by EthanB

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:@""];

回答by FreeAsInBeer

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>"
};

回答by FreeAsInBeer

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.

如果使用宏,当然只需使用可变参数即可,请参阅 EthanB 的答案。