Objective-C中用于连接NSStrings的快捷方式
Objective-C中是否有( stringByAppendingString:
string连接的快捷方式,或者一般用于处理NSString
快捷方式?
例如,我想使:
NSString *myString = @"This"; NSString *test = [myString stringByAppendingString:@" is just a test"];
更像是:
string myString = "This"; string test = myString + " is just a test";
我能想到的两个答案…既不像连接操作符那样特别愉快。
首先,使用一个NSMutableString
,它有一个appendString
方法,消除了一些额外的临时string的需要。
其次,使用NSArray
通过componentsJoinedByString
方法进行连接。
一个选项:
[NSString stringWithFormat:@"%@/%@/%@", one, two, three];
另一种select:
我猜你对多个附加(a + b + c + d)不满意,在这种情况下你可以这样做:
NSLog(@"%@", [Util append:one, @" ", two, nil]); // "one two" NSLog(@"%@", [Util append:three, @"/", two, @"/", one, nil]); // three/two/one
使用类似的东西
+ (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; }
如果你有2个NSString 文字 ,你也可以这样做:
NSString *joinedFromLiterals = @"ONE " @"MILLION " @"YEARS " @"DUNGEON!!!";
这对于join#defines也很有用:
#define STRINGA @"Also, I don't know " #define STRINGB @"where food comes from." #define JOINED STRINGA STRINGB
请享用。
我一直回到这个post,总是最终通过答案sorting,find这个简单的解决scheme,可以根据需要使用尽可能多的variables:
[NSString stringWithFormat:@"%@/%@/%@", three, two, one];
例如:
NSString *urlForHttpGet = [NSString stringWithFormat:@"http://example.com/login/username/%@/userid/%i", userName, userId];
那么,由于冒号是一种特殊的符号,但是是方法签名的一部分,所以可以用类别来扩充NSString
来添加这种非惯用的string连接风格:
[@"This " : @"feels " : @"almost like " : @"concatenation with operators"];
您可以定义尽可能多的冒号分隔参数,因为您发现有用… 😉
对于一个好的措施,我还添加了concat:
带有可变参数的string的终止列表。
// 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); }
创造一个方法……
- (NSString *)strCat: (NSString *)one: (NSString *)two { NSString *myString; myString = [NSString stringWithFormat:@"%@%@", one , two]; return myString; }
然后,无论你需要什么函数,设置你的string或textfield
或任何返回值的函数。
或者你可以做一个快捷方式是将NSString转换为一个c ++string,并在那里使用'+'。
希望这可以帮助!!!!!
使用这种方式:
NSString *string1, *string2, *result; string1 = @"This is "; string2 = @"my string."; result = [result stringByAppendingString:string1]; result = [result stringByAppendingString:string2];
要么
result = [result stringByAppendingString:@"This is "]; result = [result stringByAppendingString:@"my string."];
macros:
// 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:@""]
testing案例:
- (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"); }
备用macros:(如果你想执行最less数量的参数)
// 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:@""];
在构buildWeb服务请求时,我发现在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>" };
创buildAppendString(AS)macros的快捷方式…
#define AS(A,B)[(A)stringByAppendingString:(B)]
NSString * myString = @“This”; NSString * test = AS(myString,@“只是一个testing”);
注意:
如果使用macros,当然只是用可变参数来实现,请看下面的EthanB的答案。
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];
这是一个简单的方法,使用新的数组字面语法:
NSString * s = [@[@"one ", @"two ", @"three"] componentsJoinedByString:@""]; ^^^^^^^ create array ^^^^^ ^^^^^^^ concatenate ^^^^^
使c = [a stringByAppendingString: b]
更短的唯一方法是在st
点附近使用自动完成。 +
运算符是C的一部分,它不知道Objective-C对象。
NSString *myString = @"This"; NSString *test = [myString stringByAppendingString:@" is just a test"];
目标CI几年后,认为这是与Objective C一起工作的最佳方式,以实现您正在努力实现的目标。
在Xcode应用程序中开始键入“N”,并自动完成“NSString”。 键入“str”,并自动完成“stringByAppendingString”。 所以击键是相当有限的。
一旦你得到了打“@”键的挂钩,并且编写可读代码的过程不再成为问题。 这只是一个适应的问题。
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];
如何缩短stringByAppendingString
并使用#define :
#define and stringByAppendingString
因此你可以使用:
NSString* myString = [@"Hello " and @"world"];
问题是,它只适用于两个string,你需要包裹更多的附加括号:
NSString* myString = [[@"Hello" and: @" world"] and: @" again"];
NSString *result=[NSString stringWithFormat:@"%@ %@", @"Hello", @"World"];
在lldb
窗格中尝试以下内容
[NSString stringWithFormat:@"%@/%@/%@", three, two, one];
哪些错误。
而是使用alloc和initWithFormat
方法:
[[NSString alloc] initWithFormat:@"%@/%@/%@", @"three", @"two", @"one"];
我试过这个代码。 这是为我工作。
NSMutableString * myString=[[NSMutableString alloc]init]; myString=[myString stringByAppendingString:@"first value"]; myString=[myString stringByAppendingString:@"second string"];
这是为了更好的logging和日志logging – 基于dicius优秀的多重参数方法。 我定义了一个Logger类,并且像这样调用它:
[Logger log: @"foobar ", @" asdads ", theString, nil];
除了不得不用var结束“零”,但我想在Objective-C中没有办法解决这个问题。
Logger.h
@interface Logger : NSObject { } + (void) log: (id) first, ...; @end
Logger.m
@implementation Logger + (void) log: (id) first, ... { // TODO: make efficient; handle arguments other than strings // thanks to @diciu http://stackoverflow.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
为了只能串接string,我会在NSString上定义一个Category,然后为它添加一个静态(+)连接方法,看起来和上面的日志方法完全一样,只不过它返回string。 它在NSString上,因为它是一个string方法,它是静态的,因为你想从1-Nstring创build一个新的string,而不是在附加部分的任何一个string上调用它。
NSNumber *lat = [NSNumber numberWithDouble:destinationMapView.camera.target.latitude]; NSNumber *lon = [NSNumber numberWithDouble:destinationMapView.camera.target.longitude]; NSString *DesconCatenated = [NSString stringWithFormat:@"%@|%@",lat,lon];
试试stringWithFormat:
NSString *myString = [NSString stringWithFormat:@"%@ %@ %@ %d", "The", "Answer", "Is", 42];
经常处理string时,我发现使源文件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()];
我的首选方法是这样的:
NSString *firstString = @"foo"; NSString *secondString = @"bar"; NSString *thirdString = @"baz"; NSString *joinedString = [@[firstString, secondString, thirdString] join];
你可以通过添加一个类别的NSArray连接方法来实现它:
#import "NSArray+Join.h" @implementation NSArray (Join) -(NSString *)join { return [self componentsJoinedByString:@""]; } @end
@[]
这是NSArray
的简短定义,我认为这是串联string的最快方法。
如果您不想使用该类别,请直接使用componentsJoinedByString:
方法:
NSString *joinedString = [@[firstString, secondString, thirdString] componentsJoinedByString:@""];
你可以使用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:@" "];
要么
您可以使用
NSString *imageFullName=[NSString stringWithFormat:@"%@ %@ %@.", string1,string2,string3];
当我testing时,这些格式都可以在XCode7中使用:
NSString *sTest1 = {@"This" " and that" " and one more"}; NSString *sTest2 = { @"This" " and that" " and one more" }; NSLog(@"\n%@\n\n%@",sTest1,sTest2);
出于某种原因,您只需要在混音的第一个string上使用@运算符字符。
但是,它不适用于variables插入。 为此,您可以使用这个非常简单的解决scheme ,除了使用“cat”而不是“and”的macros。
listOfCatalogIDs =[@[@"id[]=",listOfCatalogIDs] componentsJoinedByString:@""];
在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"
另外,您可以使用+=
运算符与以下相同…
var str3 = "Some String" str3 += str2 // str3 would be "Some String is just a test"
让我们想象一下,你不知道那里有多less条琴弦。
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:@", "];
对于在UI-Test中需要这个的所有Objective 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]; }