gpt4 book ai didi

objective-c - 当数组没有任何内容时如何取出数组的第一个组件

转载 作者:行者123 更新时间:2023-11-29 13:31:12 25 4
gpt4 key购买 nike

我制作了一个只有项目符号的 TextView 。它就像 word 中的项目符号列表一样工作。现在我正在使用此代码制作一个数组,以通过项目符号 (\u2022) 分隔字符串

//get the text inside the textView
NSString *textContents = myTextView.text;

//make the array
NSArray *bulletedArray = [textContents componentsSeparatedByString:@"\u2022"];

//print out array
NSLog(@"%@",bulletedArray);

它完美地通过项目符号将文本分成多个部分,但它保留了第一行,其中没有任何内容。所以当它打印出来时看起来像这样。

"",
"Here is my first statement\n\n",
"Here is my second statement.\n\n",
"This is my third statement. "

数组的第一个组成部分是“”(无)。有没有办法避免添加等于 nil 的组件?

谢谢。

最佳答案

遗憾的是,这就是 NSStringcomponentsSeparatedBy... 方法的工作方式:

Adjacent occurrences of the separator characters produce empty strings in the result. Similarly, if the string begins or ends with separator characters, the first or last substring, respectively, is empty.

因为您知道第一个元素总是空的,所以您可以创建一个从元素 1 开始的子数组:

NSArray *bulletedArray = [textContents componentsSeparatedByString:@"\u2022"];
NSUInteger len = bulletedArray.count;
if (bulletedArray.count) {
bulletedArray = [bulletedArray subarrayWithRange:NSMakeRange(1, len-1)];
}

或者,您可以使用 substringFromIndex: 在将字符串传递给 componentsSeparatedByString: 方法之前从字符串中删除初始项目符号字符:

NSArray *bulletedArray = [
[textContents substringFromIndex:[textContents rangeOfString:@"\u2022"].location+1]
componentsSeparatedByString:@"\u2022"];

关于objective-c - 当数组没有任何内容时如何取出数组的第一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11847026/

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