Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first line in a paragraph

I am developing a iOS mobile app where my requirement is to get the first line of the paragraph and change its font from the rest of the paragraph. For e.g. - If I have a paragraph as -

let sampleString = "IS1 This is sample text.

This sample text is good. This requires to split the String into two parts. The first line is has different text from rest."

I have tried to use -

let stringToSplit = sampleString.characters.split(".").map(String.init)

But the result I am getting is - First part is coming as - IS1 This is sample text.

Remaining String is coming as - This requires to split the String into two parts. The first line is has different text from rest.

The line "This sample text is good." is not showing up.

Can you please help. XCode 8.0, Swift 2.3

Thanks.

like image 532
bably Avatar asked Dec 18 '22 10:12

bably


2 Answers

Separate the string by the newline CharacterSet, that preserves also the trailing period.

if let firstParagraph = sampleString.components(separatedBy: CharacterSet.newlines).first {
    print(firstParagraph)
}

Then you can get the range of the first paragraph in sampleString

let range = sampleString.range(of: firstParagraph)
like image 177
vadian Avatar answered Feb 25 '23 03:02

vadian


You can use following method as well to split the string

let stringToSplit = sampleString.components(separatedBy: ".")

It will return you array of components separated by given character. stringToSplit[0] will give you first sentence

like image 36
Vishnu gondlekar Avatar answered Feb 25 '23 03:02

Vishnu gondlekar