gpt4 book ai didi

iphone - NSString 组件SeparatedByString

转载 作者:行者123 更新时间:2023-12-03 20:21:02 25 4
gpt4 key购买 nike

我有一个来自服务器的字符串。我正在识别一个特定的子字符串,然后在该子字符串处断开主字符串。

NSString *string = /* getting from server */;
NSString *strAddress = /* Substring of string */;
NSArray *arr = [string componentsSeparatedByString:strAddress];
NSString *strBeforeAddress = [arr objectAtIndex:0];

strAddress 前面有一些东西时,这工作得很好。但在某些情况下,它完全给出了一个奇怪的结果。例如,当

string = @"cxzcvxcv\n14, Beaven Dam Road\nVail, CO81657";
strAddress = @"14, Beaven Dam Road\nVail, CO81657";

我在arr中只得到一个对象,即完整的字符串,我认为这是错误的。它应该以 2 个对象的形式给出结果:cxzcvxcvblank object。然而,当

string = @"14, Beaven Dam Road\nVail, CO81657";
strAddress = @"14, Beaven Dam Road\nVail, CO81657";

本例中的数组 arr 有 1 个对象,即完整的字符串。有人可以解释一下这是怎么回事吗?

最佳答案

来自NSString Class Reference关于方法 componentsSeparatedByString:

的讨论

The substrings in the array appear in the order they did in the receiver. Adjacent occurrences of the separator string produce empty strings in the result. Similarly, if the string begins or ends with the separator, the first or last substring, respectively, is empty. For example, this code fragment:

NSString *list = @"Norman, Stanley, Fletcher";

NSArray *listItems = [list componentsSeparatedByString:@", "];

produces an array { @"Norman", @"Stanley", @"Fletcher" }.

If list begins with a comma and space—for example, ", Norman, Stanley,
Fletcher"
—the array has these contents: { @"", @"Norman", @"Stanley",
@"Fletcher" }

If list has no separators—for example, "Norman"—the array contains the string itself, in this case { @"Norman" }.

两个测试用例的输出是:

NSString *string = @"cxzcvxcv\n14, Beaven Dam Road\nVail, CO81657";
NSString *strAddress = @"14, Beaven Dam Road\nVail, CO81657";
NSLog(@"%@",[string componentsSeparatedByString:strAddress]);

输出

(
"cxzcvxcv\n",
""
)
正如预期的那样。对于第二种情况

NSString *string = @"14, Beaven Dam Road\nVail, CO81657";
NSString *strAddress = @"14, Beaven Dam Road\nVail, CO81657";
NSLog(@"%@",[string componentsSeparatedByString:strAddress]);

输出

(
"",
""
)

再次,正如预期的那样。我认为这里没有问题。

关于iphone - NSString 组件SeparatedByString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8906221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com