如何获取字符串中第一行的范围

如何获取字符串中第一行的范围

本文介绍了如何获取字符串中第一行的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改 NSTextView 中第一行文本的格式(给它一个不同的字体大小和粗细,使其看起来像一个标题).因此,我需要第一行的范围.一种方法是这样的:

I would like to change the formatting of the first line of text in an NSTextView (give it a different font size and weight to make it look like a headline). Therefore, I need the range of the first line. One way to go is this:

guard let firstLineString = textView.string.components(separatedBy: .newlines).first else {
    return
}
let range = NSRange(location: 0, length: firstLineString.count)

但是,我可能正在处理很长的文本,因此当我只需要第一行组件时,首先将整个字符串拆分为行组件似乎效率低下.因此,使用 firstIndex(where:) 方法似乎是有意义的:

However, I might be working with quite long texts so it appears to be inefficient to first split the entire string into line components when all I need is the first line component. Thus, it seems to make sense to use the firstIndex(where:) method:

let firstNewLineIndex = textView.string.firstIndex { character -> Bool in
    return CharacterSet.newlines.contains(character)
}
// Then: Create an NSRange from 0 up to firstNewLineIndex.

这不起作用,我收到一个错误:

This doesn't work and I get an error:

无法转换类型 '(Unicode.Scalar) -> 的值Bool' 到预期的参数类型 'Character'

因为 contains 方法接受的不是 Character 而是 Unicode.Scalar 作为参数(这对我来说没有意义因为那样它应该被称为 UnicodeScalarSet 而不是 CharacterSet,但没关系...)

because the contains method accepts not a Character but a Unicode.Scalar as a parameter (which doesn't really make sense to me because then it should be called a UnicodeScalarSet and not a CharacterSet, but nevermind...).

我的问题是:

(不一定必须使用 firstIndex(where:) 方法,但似乎是要走的路.)

(It doesn't necessarily have to use the firstIndex(where:) method, but appears to be the way to go.)

推荐答案

string 中第一行的 String.Index 范围可以通过

A String.Index range for the first line in string can be obtained with

let range = string.lineRange(for: ..<string.startIndex)

如果你需要它作为 NSRange 那么

If you need that as an NSRange then

let nsRange = NSRange(range, in: string)

成功了.

这篇关于如何获取字符串中第一行的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:58