In a mobile App I use an API that can only handle about 300 words. How can I trimm a string in Swift so that it doesn't contain more words?
The native .trimmingCharacters(in: CharacterSet)
does not seem to be able to do this as it is intended to trimm certain characters.
There is no off-the shelf way to limit the number of words in a string.
If you look at this post, it documents using the method
enumerateSubstrings(in: Range)
and setting an option of .byWords. It looks like it returns an array ofRange
values.You could use that to create an extension on String that would return the first X words of that string:
If we then run the code:
The output is:
Using
enumerateSubstrings(in: Range)
is going to give much better results than splitting your string using spaces, since there are a lot more separators than just spaces in normal text (newlines, commas, colons, em spaces, etc.) It will also work for languages like Japanese and Chinese that often don't have spaces between words.You might be able to rewrite the function to terminate the enumeration of the string as soon as it reaches the desired number of words. If you want a small percentage of the words in a very long string that would make it significantly faster (the code above should have
O(n)
performance, although I haven't dug deeply enough to be sure of that. I also couldn't figure out how to terminate theenumerateSubstrings()
function early, although I didn't try that hard.)Leo Dabus provided an improved version of my function. It extends StringProtocol rather than String, which means it can work on substrings. Plus, it stops once it hits your desired word count, so it will be much faster for finding the first few words of very long strings: