# Additional String Processing APIs

**URL:** <https://forums.swift.org/t/additional-string-processing-apis/36255>\
**Category:** Discussion\
**Tags:** string\
**Created:** [May 7, 2020, 4:31pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255 "2020-05-07T16:31:25Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![barnard-b](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/barnard-b/32/10313_2.png) [@barnard-b](https://forums.swift.org/u/barnard-b)\
**Post date:** [May 7, 2020, 4:31pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/1 "2020-05-07T16:31:25Z")

</div>

The purpose of the thread is to determine what APIs (if any) the community needs for string manipulation that are not currently available.

For example, [filtering by character set](https://forums.swift.org/t/string-without-characters-in-set/19192) and [string padding](https://forums.swift.org/t/string-without-characters-in-set/19192/17) have been mentioned in the past.

* * *

If you have an API idea, some helpful things to include would be:

- What are you trying to achieve?
- What do you envision the new API looking like?
- How would this be achieved today?

---

<div class="post-metadata">

**Author:** ![wowbagger](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/wowbagger/32/13847_2.png) [@wowbagger](https://forums.swift.org/u/wowbagger)\
**Post date:** [May 7, 2020, 4:48pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/2 "2020-05-07T16:48:04Z")

</div>

In general, I think it will be great if most of `NSString`'s APIs are moved to `String`. Some of them might not be exactly appropriate for `String`. For example, APIs for working with paths in `NSString` are probably more appropriate if they are reproduced in `URL`.

---

<div class="post-metadata">

**Author:** ![Karl](https://avatars.discourse-cdn.com/v4/letter/k/34f0e0/32.png) [@Karl](https://forums.swift.org/u/Karl)\
**Post date:** [May 7, 2020, 6:50pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/3 "2020-05-07T18:50:21Z")

</div>

Two major issues come to mind:

- In-place substitution only exists on `NSMutableString` (`NSMS.replaceOccurences(of: String, with: String, options: NSString.CompareOptions, range: NSRange`). If you start with a Swift String, this means bridging to NSMS, performing the replacements, then bridging back. This is a pretty basic feature, and we should do better.

- ASCII string processing. Currently I'm working on parsing data formats that only accept ASCII strings, and the overheads from the unicode model are a significant performance drain. We pay for every call to `index(after:)`, even though we check every character and will ultimately fail if any of them are non-ASCII!

---

<div class="post-metadata">

**Author:** ![davedelong](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/davedelong/32/38708_2.png) [@davedelong](https://forums.swift.org/u/davedelong)\
**Post date:** [May 7, 2020, 7:37pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/4 "2020-05-07T19:37:34Z")

</div>

I've been missing things around symmetry and complementing existing APIs. For example, we have ways to check if a `String` begins or ends with another `String` (`hasPrefix(_:)` and `hasSuffix(_:)`), but we don't have an easy way to remove them if they're present, such as:

```swift
mutating func removePrefix(_ prefix: String)
func removingPrefix(_ prefix: String) -> String

mutating func removeSuffix(_ suffix: String)
func removingSuffix(_ suffix: String) -> String

```

Sometimes I'll need to capitalize the first letter of a string, but not capitalize every word (like `capitalized(with:)` does):

```swift
func capitalizingFirstLetter(with locale: Locale? = nil) -> String

```

---

<div class="post-metadata">

**Author:** ![Dante-Broggi](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dante-broggi/32/7955_2.png) [@Dante-Broggi](https://forums.swift.org/u/Dante-Broggi)\
**Post date:** [May 7, 2020, 8:05pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/5 "2020-05-07T20:05:21Z")

</div>

One function I noticed as missing is a Unicode-correct `casefolded` implementation.  
This is different from `lowercased` as some characters go to their uppercase forms.

Also, a stdlib case-ignoring string wrapper/view would probably be more Unicode-correct than whatever most can come up with.

---

<div class="post-metadata">

**Author:** ![grantjbutler](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/grantjbutler/32/11599_2.png) [@grantjbutler](https://forums.swift.org/u/grantjbutler)\
**Post date:** [May 7, 2020, 8:59pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/6 "2020-05-07T20:59:52Z")

</div>

Want to +1 these prefix and suffix methods. Had a use case for them recently. Would be nice to see them as part of the standard library.

---

<div class="post-metadata">

**Author:** ![barnard-b](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/barnard-b/32/10313_2.png) [@barnard-b](https://forums.swift.org/u/barnard-b)\
**Post date:** [May 8, 2020, 12:26am UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/7 "2020-05-08T00:26:59Z")

</div>

> [@Karl](#):
>
> In-place substitution only exists on `NSMutableString`

Hmm, it seems that most substitution (including [`StringProtocol.replacingOccurrences(of:with:options:range:)`](https://developer.apple.com/documentation/swift/stringprotocol/3126775-replacingoccurrences)) is part of Foundation and not the standard library (Probably due to [`String.CompareOptions`](https://developer.apple.com/documentation/swift/string/compareoptions) being a type alias of [`NSString.CompareOptions`](https://developer.apple.com/documentation/foundation/nsstring/compareoptions)).

> [@davedelong](#):
>
> Sometimes I'll need to capitalize the first letter of a string, but not capitalize every word (like `capitalized(with:)` does):

[`capitalized(with:)`](https://developer.apple.com/documentation/swift/stringprotocol/2923387-capitalized) is also in Foundation (because of [`Locale`](https://developer.apple.com/documentation/foundation/locale)).

Since evolution [does not cover Foundation](https://forums.swift.org/t/where-do-proposals-for-improvements-to-apple-swift-api-wrappers-go/18518/7), changes like this would be separate from a normal pitch.

---

<div class="post-metadata">

**Author:** ![barnard-b](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/barnard-b/32/10313_2.png) [@barnard-b](https://forums.swift.org/u/barnard-b)\
**Post date:** [May 8, 2020, 12:32am UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/8 "2020-05-08T00:32:17Z")

</div>

I have started cateloging the changes suggested (work in progress).

> **[GitHub - barnard-b/Swift-String-API-Ideas: Ideas for new String APIs - Swift...](https://github.com/barnard-b/Swift-String-API-Ideas)**
>
> Ideas for new String APIs - Swift Programming Language - GitHub - barnard-b/Swift-String-API-Ideas: Ideas for new String APIs - Swift Programming Language

Edit: Sorry, meant to create a general reply not a post reply.

---

<div class="post-metadata">

**Author:** ![Jon\_Shier](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jon_shier/32/921_2.png) [@Jon\_Shier](https://forums.swift.org/u/Jon_Shier)\
**Post date:** [May 8, 2020, 12:46am UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/9 "2020-05-08T00:46:03Z")

</div>

Many `String` processing algorithms can also be applied to `Sequence`s or `Collection`s in general, so suggest we start there. There have been discussions in the past, including an [Offset indexing pitch](https://forums.swift.org/t/call-for-users-and-authors-offset-indexing-pitch/21444) which would be useful, among others.

---

<div class="post-metadata">

**Author:** ![wowbagger](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/wowbagger/32/13847_2.png) [@wowbagger](https://forums.swift.org/u/wowbagger)\
**Post date:** [May 8, 2020, 12:54am UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/10 "2020-05-08T00:54:37Z")

</div>

I think what @Karl and @davedelong meant is that they want some of `NSMutableString`, `NSString`, etc's methods reproduced in `String`. I don't think we need to change anything in `Foundation` at all for that. We can leave it be, and just add whatever functionality we need into `String`.

---

<div class="post-metadata">

**Author:** ![jayton](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jayton/32/5592_2.png) [@jayton](https://forums.swift.org/u/jayton)\
**Post date:** [May 8, 2020, 9:51am UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/11 "2020-05-08T09:51:32Z")

</div>

I would also like to see more convenient “ASCII” parsing, with the caveat that this often means the structure of a file is ASCII-range characters, but some content such as strings or comments may be UTF-8.

Addendum: in the context of Swift, this isn’t necessarily a `String` thing; `Data` or pointer types may be more appropriate, if we had a solution to the zero-cost ergonomic ASCII character literal problem. It just springs to mind here because strings and text-or-text-like-data-processing are closely related.

> [@wowbagger](#):
>
> I think what @Karl and @davedelong meant is that they want some of `NSMutableString` , `NSString` , etc's methods reproduced in `String` . I don't think we need to change anything in `Foundation` at all for that. We can leave it be, and just add whatever functionality we need into `String` .

This would perhaps be reasonable for things like literal search and replace, but case-insensitive/diacritic-insensitive search and capitalization are probably non-starters since there’s no concept of languages or locales in the standard library. For literal searching, generic `Collection` and `Sequence` solutions should probably be preferred to string-specific ones.

---

<div class="post-metadata">

**Author:** ![barnard-b](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/barnard-b/32/10313_2.png) [@barnard-b](https://forums.swift.org/u/barnard-b)\
**Post date:** [May 8, 2020, 11:06pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/13 "2020-05-08T23:06:13Z")

</div>

> [@wtedst](#):
>
> I guess in this case you really need to encode the "if present" part somehow: either by naming the methods `removePrefixIfPresent` or by using the `Set` 's convention of returning the optional of the element if it was found and removed or `nil` otherwise.

There is precedent for returning the removed value (For example: [`removeFirst() -> Character`](https://developer.apple.com/documentation/swift/string/2892519-removefirst)), there is also precedent for not returning anything ([`removeSubrange(_:)`](https://developer.apple.com/documentation/swift/string/3018536-removesubrange)). Personally, I think returning a discardable optional would give developers the most flexibility.

> [@wtedst](#):
>
> That is, should `"ABCD".removePrefix("ABCZ")` remove the first three letters or do nothing at all? How does it communicate this decision?

Only a complete match should be acted upon. In general Swift is very explicit, so we should be ok as long as the behavior pattern of the new API fits with `hasPrefix`/`hasSuffix` (and there is proper documentation).

---

<div class="post-metadata">

**Author:** ![Karl](https://avatars.discourse-cdn.com/v4/letter/k/34f0e0/32.png) [@Karl](https://forums.swift.org/u/Karl)\
**Post date:** [May 9, 2020, 6:35am UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/15 "2020-05-09T06:35:10Z")

</div>

> [@wowbagger](#):
>
> I think what @Karl and @davedelong meant is that they want some of `NSMutableString` , `NSString` , etc's methods reproduced in `String` . I don't think we need to change anything in `Foundation` at all for that. We can leave it be, and just add whatever functionality we need into `String` .

Yes, this functionality should be in the standard library. You shouldn't need Foundation for basic find/replace.

Of course, they are in Foundation right now, because Foundation is used to owning its own String type, as well as all the other basic types, since it is the "standard library" for Objective-C.

Locale-dependent searching is an interesting question. I don't know enough about unicode to say whether our String type requires locales for correctness, but if it does I would be in favour of lifting that to the standard library, too.

---

<div class="post-metadata">

**Author:** ![barnard-b](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/barnard-b/32/10313_2.png) [@barnard-b](https://forums.swift.org/u/barnard-b)\
**Post date:** [May 11, 2020, 6:19pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/16 "2020-05-11T18:19:16Z")

</div>

> [@Karl](#):
>
> Yes, this functionality should be in the standard library. You shouldn't need Foundation for basic find/replace.  
> ...  
> Locale-dependent searching is an interesting question. I don't know enough about unicode to say whether our String type requires locales for correctness, but if it does I would be in favour of lifting that to the standard library, too.

After a cursory look at the implementation of `replacingOccurrences(of:with:options:range:)` in [`swift-corelibs-foundation`](https://github.com/apple/swift-corelibs-foundation), it appears that Unicode processing (case folding?) is used. Not sure if this is required because of the case insensitive search option or just needed in general.

> **Call Stack for replacingOccurrences**
>
> 1. [`StringProtocol.replacingOccurrences`](https://github.com/apple/swift-corelibs-foundation/blob/c1fee3a0c8c9f87a67997ff92769fac78fe6cda7/Sources/Foundation/NSStringAPI.swift#L1116)
> 2. [`NSString.replacingOccurrences`](https://github.com/apple/swift-corelibs-foundation/blob/ea504974c6e0b681743a1847a108d6f34fc5b5f6/Sources/Foundation/NSString.swift#L1218)
> 3. [`NSMutableString.replaceOccurrences`](https://github.com/apple/swift-corelibs-foundation/blob/ea504974c6e0b681743a1847a108d6f34fc5b5f6/Sources/Foundation/NSString.swift#L1556)
> 4. [`CFStringCreateArrayWithFindResults`](https://github.com/apple/swift-corelibs-foundation/blob/42bfad499c4e938156d5b49331c75f69cc92798c/CoreFoundation/String.subproj/CFString.c#L3418)
> 5. [`CFStringFindWithOptions`](https://github.com/apple/swift-corelibs-foundation/blob/42bfad499c4e938156d5b49331c75f69cc92798c/CoreFoundation/String.subproj/CFString.c#L3393)
> 6. [`CFStringFindWithOptionsAndLocale`](https://github.com/apple/swift-corelibs-foundation/blob/42bfad499c4e938156d5b49331c75f69cc92798c/CoreFoundation/String.subproj/CFString.c#L2984)
> 7. [`__CFStringFoldCharacterClusterAtIndex`](https://github.com/apple/swift-corelibs-foundation/blob/42bfad499c4e938156d5b49331c75f69cc92798c/CoreFoundation/String.subproj/CFString.c#L2399)

I will work on a proof of concept replace extension and see what happens.

---

<div class="post-metadata">

**Author:** ![Jens](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jens/32/12903_2.png) [@Jens](https://forums.swift.org/u/Jens)\
**Post date:** [May 11, 2020, 8:27pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/17 "2020-05-11T20:27:40Z")

</div>

Not sure if this is relevant, but there's things like:

```swift
let s = "ß"
print(s.lowercased()) // ß
print(s.uppercased()) // SS
print(s.capitalized) // Ss

```

And I guess a whole lot of even more complicated stuff related to other languages than german.

---

<div class="post-metadata">

**Author:** ![wowbagger](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/wowbagger/32/13847_2.png) [@wowbagger](https://forums.swift.org/u/wowbagger)\
**Post date:** [May 11, 2020, 9:03pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/18 "2020-05-11T21:03:04Z")

</div>

Adding to @Jens's "ß" example, here is one with Turkish alphabet:

```swift
let i = "i"
let ı = "ı"
let İ = "İ"
let I = "I"

print(i.uppercased()) // I
print(ı.uppercased()) // I
print(İ.lowercased()) // i
print(I.lowercased()) // i

```

In Turkish, "i" and "İ" are the same letter, and "ı" and "I" the same. Because of the lack of locale-awareness in `String`, both "ı" and "i" are capitalised to "I", and 'I" and "İ" to "i".

I'm not sure how much it will help `String` by giving it locale-awareness though, since many texts contain multiple languages.

Ligatures in fonts are also affected by this, but that probably falls in `NSFontManager`'s domain, not really in `String`'s.

On another mostly unrelated note, this is often a supporting case for case-sensitive file systems.

---

<div class="post-metadata">

**Author:** ![uliwitness](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/uliwitness/32/6272_2.png) [@uliwitness](https://forums.swift.org/u/uliwitness)\
**Post date:** [May 12, 2020, 6:21pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/19 "2020-05-12T18:21:42Z")

</div>

I recently tried to implement a tokenizer in Swift, and it was very awkward to do with `NSScanner` (as it seems to be aimed more at ad-hoc date parsing and the like where you don't need to store parse offsets etc.), and not obviously supported in `String` at all. And given it is a bit complicated to perform arithmetics on `String.Index` correctly, it would be helpful to make such things easier and more efficient.

In particular, a way to iterate over a `String` and test whether a certain string or sequence from a `CharacterSet` is present, and to also get their `Range` in the `String` would be really helpful. Something like

```swift
extension String {
    func extractIf(prefix: String, in range: inout Range) -> (String, Range)?
    func extracLongesttIf(prefixFrom: CharacterSet, in range: inout Range) -> (String, Range)?
}

```

This would take the search range and update it to exclude the characters just found, so you can just call this repeatedly with a `var searchRange = Range(location: 0, length: myString.count)` that then is updated by each subsequent call.

---

<div class="post-metadata">

**Author:** ![uliwitness](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/uliwitness/32/6272_2.png) [@uliwitness](https://forums.swift.org/u/uliwitness)\
**Post date:** [May 12, 2020, 6:28pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/20 "2020-05-12T18:28:28Z")

</div>

FWIW, while the general idea of letters that don't have an uppercase version or have one that consists of other characters probably exists in other languages (if you leave aside languages like Japanese that don't even have the concept of case), this example in practice is not really useful:

There are no words that start with a sharp-S, so the `capitalized()` version will never occur in practice. Also, a few years ago the capital letter for sharp-S was standardized by the German ministries of education of all the states, so a better solution for `uppercased()`would be to finally update macOS keyboard layouts to allow typing that letter and leave Swift alone in this particular case.

---

<div class="post-metadata">

**Author:** ![CTMacUser](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ctmacuser/32/1802_2.png) [@CTMacUser](https://forums.swift.org/u/CTMacUser)\
**Post date:** [May 12, 2020, 11:27pm UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/21 "2020-05-12T23:27:57Z")

</div>

> [@barnard-b](#):
>
> > [@wtedst](#):
> >
> > That is, should `"ABCD".removePrefix("ABCZ")` remove the first three letters or do nothing at all? How does it communicate this decision?
> 
> Only a complete match should be acted upon. In general Swift is very explicit, so we should be ok as long as the behavior pattern of the new API fits with `hasPrefix` / `hasSuffix` (and there is proper documentation).

A function that removes on partial prefixes can be composed from the whole-prefix version along with a [divergence-testing method](https://forums.swift.org/t/an-official-proposal-for-diverges-from/15279).

> [@uliwitness](#):
>
> In particular, a way to iterate over a `String` and test whether a certain string or sequence from a `CharacterSet` is present, and to also get their `Range` in the `String` would be really helpful. Something like
> 
> ```
> extension String {
> func extractIf(prefix: String, in range: inout Range) -> (String, Range)?
> func extracLongesttIf(prefixFrom: CharacterSet, in range: inout Range) -> (String, Range)?
> }
> 
> ```

`extractIf` could be done with a divergence-testing function too. `extractLongestIf` could be adapted from `self.firstIndex(where: { !prefixFrom.contains($0) })`. Neither requires `String`; they should be added to `Collection` in general.

---

<div class="post-metadata">

**Author:** ![Wildchild9](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/wildchild9/32/9397_2.png) [@Wildchild9](https://forums.swift.org/u/Wildchild9)\
**Post date:** [May 13, 2020, 1:02am UTC](https://forums.swift.org/t/additional-string-processing-apis/36255/22 "2020-05-13T01:02:14Z")

</div>

One thing that I feel is missing from strings in Swift is parsing.

A primary aspect of parsing that is currently clunky, difficult to use, and lacking in some regards is regular expressions. To start off, you have to import Foundation to be able to do anything with regular expressions in the first place. While there are currently a few methods that allow you to somewhat easily work with regular expressions by using `.regularExpression` option (`replacingOccurrences(of:with:options:)` and `range(of:options:)`), they aren't always sufficient and you often need to work with `NSRegularExpression`. This is were I largely take issue. I also got some discussion going regarding some of the issues with regular expressions [here](https://forums.swift.org/t/regular-expressions-in-swift/34373) by the way. Anyways, `NSRegularExpression` is not a very swifty API and is often a pain to use. Working with capture groups and matches is also not very easy. I feel that a native Swift implementation that provides an API that leverages Swift's features would be quite helpful. Maybe even provide first-class regex support with a unique literal syntax with highlighting 🤷‍♂️. @Michael_Ilseman came up with some ideas regarding how this could work in his [State of String: ABI, Performance, Ergonomics, and You!](https://gist.github.com/milseman/bb39ef7f170641ae52c13600a512782f#one-possible-approach) doc. And even if it is not feasible to provide custom syntax and whatnot, I feel that a native Swift solution in some capacity is needed.

On a more general note though, I feel that we should look into what can be done to make parsing strings easer. I'm not sure how we can go about this, but, when trying to create a program that tokenized and parsed strings, I found that it got very complicated very quickly. I feel like there must be a better way, though I'm not really sure.

[Next page](https://forums.swift.org/t/additional-string-processing-apis/36255.md?page=2)
