Skróty w Objective-C do łączenia NSStrings
Czy są jakieś skróty do (stringByAppendingString:
) konkatenacji łańcuchów w Objective-C, lub skróty do pracy z NSString
w ogóle?
Na przykład, chciałbym zrobić:
NSString *myString = @"This";
NSString *test = [myString stringByAppendingString:@" is just a test"];
Coś bardziej jak:
string myString = "This";
string test = myString + " is just a test";
30 answers
Dwie odpowiedzi... żadna z nich nie jest szczególnie przyjemna, jak tylko posiadanie operatora konkatenacji.
Najpierw użyj NSMutableString
, która ma metodę appendString
, usuwając potrzebę dodatkowych ciągów temp.
Po drugie, użyj NSArray
do połączenia metodą componentsJoinedByString
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-22 03:12:57
Opcja:
[NSString stringWithFormat:@"%@/%@/%@", one, two, three];
Inna opcja:
Zgaduję, że nie jesteś zadowolony z wielu dodatków (a+b+c+d), w takim przypadku możesz to zrobić:
NSLog(@"%@", [Util append:one, @" ", two, nil]); // "one two"
NSLog(@"%@", [Util append:three, @"/", two, @"/", one, nil]); // three/two/one
Używanie czegoś w rodzaju
+ (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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-17 22:18:42
Jeśli masz 2 NSString literały , Możesz również zrobić to:
NSString *joinedFromLiterals = @"ONE " @"MILLION " @"YEARS " @"DUNGEON!!!";
Jest to również przydatne do łączenia # definiuje:
#define STRINGA @"Also, I don't know "
#define STRINGB @"where food comes from."
#define JOINED STRINGA STRINGB
Smacznego.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-20 14:54:53
Ciągle wracam do tego postu i zawsze kończę sortowanie odpowiedzi, aby znaleźć proste rozwiązanie, które działa z tak wieloma zmiennymi, jak potrzeba:
[NSString stringWithFormat:@"%@/%@/%@", three, two, one];
Na przykład:
NSString *urlForHttpGet = [NSString stringWithFormat:@"http://example.com/login/username/%@/userid/%i", userName, userId];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-20 05:20:01
Utwórz metodę:
- (NSString *)strCat: (NSString *)one: (NSString *)two
{
NSString *myString;
myString = [NSString stringWithFormat:@"%@%@", one , two];
return myString;
}
Następnie, w dowolnej funkcji, której potrzebujesz, Ustaw swój łańcuch znaków lub pole tekstowe lub cokolwiek na wartość zwracaną tej funkcji.
Lub, aby utworzyć skrót, przekonwertuj NSString na ciąg C++ i użyj tam'+'.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-06 04:30:50
Cóż, ponieważ dwukropek jest rodzajem specjalnego symbolu, ale jest częścią podpisu metody, możliwe jest wyjście NSString
z kategorią, aby dodać ten nie-idiomatyczny styl konkatenacji łańcuchów:
[@"This " : @"feels " : @"almost like " : @"concatenation with operators"];
Możesz zdefiniować tyle argumentów oddzielonych dwukropkami, ile uznasz za użyteczne... ;-)
Dla dobrej miary dodałem również {[3] } ze zmiennymi argumentami, które pobierają nil
zakończoną listę łańcuchów.
// 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);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-19 09:20:49
Użyj stringByAppendingString:
w ten sposób:
NSString *string1, *string2, *result;
string1 = @"This is ";
string2 = @"my string.";
result = [result stringByAppendingString:string1];
result = [result stringByAppendingString:string2];
Lub
result = [result stringByAppendingString:@"This is "];
result = [result stringByAppendingString:@"my string."];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-03 15:30:07
Makro:
// 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:@""]
Przypadki Testowe:
- (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");
}
Alternatywne makro: (jeśli chcesz wymusić minimalną liczbę argumentów)
// 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:@""];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-31 17:07:51
Podczas tworzenia żądań dla usług internetowych, uważam, że zrobienie czegoś takiego jest bardzo łatwe i sprawia, że konkatenacja jest czytelna w 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>"
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-16 14:24:43
Skrót poprzez utworzenie makra AppendString (AS)...
#define AS(A,B) [(A) stringByAppendingString:(B)]
NSString *myString = @"This"; NSString *test = AS(myString,@" is just a test");
Uwaga:
Jeśli używasz makra, oczywiście rób to z zmiennymi argumentami, zobacz odpowiedź EthanB.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-14 10:03:18
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];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-10 09:58:30
Oto prosty sposób, używając nowej składni tablicy:
NSString * s = [@[@"one ", @"two ", @"three"] componentsJoinedByString:@""];
^^^^^^^ create array ^^^^^
^^^^^^^ concatenate ^^^^^
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-30 02:29:57
NSString *myString = @"This";
NSString *test = [myString stringByAppendingString:@" is just a test"];
Po kilku latach pracy z Objective C myślę, że jest to najlepszy sposób pracy z Objective C, aby osiągnąć to, co próbujesz osiągnąć.
Zacznij keying w "N" w aplikacji Xcode i automatycznie uzupełnia się do "NSString". klucz w " str "i automatycznie uzupełnia się do "stringByAppendingString". Więc naciśnięcia klawiszy są dość ograniczone.
Po naciśnięciu klawisza " @ " i zaksięgowaniu proces pisania czytelnego kodu nie staje się już problemem. To tylko kwestia adaptacji.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-01 13:13:10
Jedynym sposobem na skrócenie c = [a stringByAppendingString: b]
jest użycie autouzupełniania wokół punktu st
. Operator +
jest częścią C, która nie wie o obiektach Objective-C.
Może skrócenie stringByAppendingString
i użycie #define :
#define and stringByAppendingString
W ten sposób można by użyć:
NSString* myString = [@"Hello " and @"world"];
Problem polega na tym, że działa tylko dla dwóch ciągów znaków, musisz zawinąć dodatkowe nawiasy, aby uzyskać więcej załączników:
NSString* myString = [[@"Hello" and: @" world"] and: @" again"];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-03 22:36:29
NSString *result=[NSString stringWithFormat:@"%@ %@", @"Hello", @"World"];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-29 07:53:24
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];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-24 01:09:13
Próbowałem tego kodu. u mnie działa.
NSMutableString * myString=[[NSMutableString alloc]init];
myString=[myString stringByAppendingString:@"first value"];
myString=[myString stringByAppendingString:@"second string"];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-02 19:55:32
Próbowano wykonać następujące czynności w okienku lldb
[NSString stringWithFormat:@"%@/%@/%@", three, two, one];
Jakie błędy.
Zamiast tego użyj metody alloc i initWithFormat
:
[[NSString alloc] initWithFormat:@"%@/%@/%@", @"three", @"two", @"one"];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-03 04:37:42
To jest dla lepszego logowania, i logowania tylko-oparte na dicius excellent multiple argument method. Definiuję klasę Loggera i nazywam ją tak:
[Logger log: @"foobar ", @" asdads ", theString, nil];
Prawie dobrze, z wyjątkiem konieczności zakończenia var args przez "nil", ale przypuszczam, że nie można tego obejść w 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
Aby tylko concat, zdefiniowałbym kategorię na NSString i dodał do niej statyczną (+) metodę concatenate, która wygląda dokładnie tak powyższa metoda log z tą różnicą, że zwraca łańcuch. Jest na NSString, ponieważ jest to metoda łańcuchowa, i jest statyczna, ponieważ chcesz utworzyć nowy łańcuch z 1 - N łańcuchów, a nie wywoływać go na żadnym z łańcuchów, które są częścią dopisywania.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-23 17:37:16
NSNumber *lat = [NSNumber numberWithDouble:destinationMapView.camera.target.latitude];
NSNumber *lon = [NSNumber numberWithDouble:destinationMapView.camera.target.longitude];
NSString *DesconCatenated = [NSString stringWithFormat:@"%@|%@",lat,lon];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-20 13:42:37
Spróbuj stringWithFormat:
NSString *myString = [NSString stringWithFormat:@"%@ %@ %@ %d", "The", "Answer", "Is", 42];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-11 18:28:04
Kiedy mam do czynienia z ciągami często łatwiej jest mi zrobić plik źródłowy ObjC++, wtedy mogę połączyć std:: strings używając drugiej metody pokazanej w pytaniu.
std::string stdstr = [nsstr UTF8String];
//easier to read and more portable string manipulation goes here...
NSString* nsstr = [NSString stringWithUTF8String:stdstr.c_str()];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-14 13:41:42
Moja preferowana metoda jest taka:
NSString *firstString = @"foo";
NSString *secondString = @"bar";
NSString *thirdString = @"baz";
NSString *joinedString = [@[firstString, secondString, thirdString] join];
Możesz to osiągnąć dodając metodę join do nsArray z kategorią:
#import "NSArray+Join.h"
@implementation NSArray (Join)
-(NSString *)join
{
return [self componentsJoinedByString:@""];
}
@end
@[]
jest to krótka definicja NSArray
, myślę, że jest to najszybsza Metoda łączenia łańcuchów.
Jeśli nie chcesz używać kategorii, użyj bezpośrednio metody componentsJoinedByString:
:
NSString *joinedString = [@[firstString, secondString, thirdString] componentsJoinedByString:@""];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-03 17:29:12
Możesz użyć NSArray jako
NSString *string1=@"This"
NSString *string2=@"is just"
NSString *string3=@"a test"
NSArray *myStrings = [[NSArray alloc] initWithObjects:string1, string2, string3,nil];
NSString *fullLengthString = [myStrings componentsJoinedByString:@" "];
Lub
Możesz użyć
NSString *imageFullName=[NSString stringWithFormat:@"%@ %@ %@.", string1,string2,string3];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-17 05:32:10
Jeden z tych formatów działa w XCode7 kiedy testowałem:
NSString *sTest1 = {@"This" " and that" " and one more"};
NSString *sTest2 = {
@"This"
" and that"
" and one more"
};
NSLog(@"\n%@\n\n%@",sTest1,sTest2);
Z jakiegoś powodu potrzebujesz tylko znaku operatora @ na pierwszym ciągu miksu.
Jednak nie działa z wstawianiem zmiennych. W tym celu możesz użyć tego niezwykle prostego rozwiązania z wyjątkiem użycia makra na "cat" zamiast "and".
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:45
Dla wszystkich miłośników Objective C, którzy potrzebują tego w UI-teście:
-(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];
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-07 08:45:00
listOfCatalogIDs =[@[@"id[]=",listOfCatalogIDs] componentsJoinedByString:@""];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-22 04:10:27
Wyobraźmy sobie, że nie wiesz, ile strun tam jest.
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:@", "];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-27 08:08:35
Zainspirowany NSMutableString
pomysłem Chrisa, robię idealne makro imho.
Obsługuje wstawianie żadnych elementów bez żadnych WYJĄTKÓW.
#import <libextobjc/metamacros.h>
#define STR_CONCAT(...) \
({ \
__auto_type str__ = [NSMutableString string]; \
metamacro_foreach_cxt(never_use_immediately_str_concatify_,, str__, __VA_ARGS__) \
(NSString *)str__.copy; \
})
#define never_use_immediately_str_concatify_(INDEX, CONTEXT, VAR) \
[CONTEXT appendString:VAR ?: @""];
Przykład:
STR_CONCAT(@"button_bg_", @(count).stringValue, @".png");
// button_bg_2.png
Jeśli chcesz, możesz użyć id
type jako parametru używając [VAR description]
zamiast NSString
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-16 05:09:04