Reputation: 1085
I made a textview that is bulleted only. It works just like a bulleted list in word. Now I am making an array using this code to separate strings by a bullet point (\u2022)
//get the text inside the textView
NSString *textContents = myTextView.text;
//make the array
NSArray *bulletedArray = [textContents componentsSeparatedByString:@"\u2022"];
//print out array
NSLog(@"%@",bulletedArray);
It works perfectly with separating the text into components by bullet points but it keeps the first line that has nothing in it. So when it prints out it looks like this.
"",
"Here is my first statement\n\n",
"Here is my second statement.\n\n",
"This is my third statement. "
The very first component of the array is "" (nothing). Is there a way to avoid adding components that equal nil?
Thanks.
Upvotes: 1
Views: 153
Reputation: 2999
while your bulleted list has always a bullet on index 1, you can simply cut the first index out of the string:
//get the text inside the textView
if (myTextView.text.length > 1) {
NSString *textContents =[myTextView.text substringFromIndex:2];
//make the array
NSArray *bulletedArray = [textContents componentsSeparatedByString:@"\u2022"];
//print out array
NSLog(@"%@",bulletedArray);
}
of course you should avoid having an empty text, while this would cause an arrayOutOfBounds Exception.
Upvotes: 0
Reputation: 726779
Sadly, this is the way the componentsSeparatedBy...
methods of NSString
work:
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.
Since you know that the first element will always be empty, you can make a sub-array starting at element 1
:
NSArray *bulletedArray = [textContents componentsSeparatedByString:@"\u2022"];
NSUInteger len = bulletedArray.count;
if (bulletedArray.count) {
bulletedArray = [bulletedArray subarrayWithRange:NSMakeRange(1, len-1)];
}
Alternatively, you can use substringFromIndex:
to chop off the initial bullet character from the string before passing it to the componentsSeparatedByString:
method:
NSArray *bulletedArray = [
[textContents substringFromIndex:[textContents rangeOfString:@"\u2022"].location+1]
componentsSeparatedByString:@"\u2022"];
Upvotes: 1
Reputation: 1615
[[NSMutableArray arrayWithArray:[textContents componentsSeparatedByString:@"\u2022"]] removeObjectIdenticalTo:@""];
that should do the trick
Upvotes: 0