user6631185
user6631185

Reputation:

How to get frequency of line feed in string by swift

Sorry,I'm new of swift. I want to calculate the target char in string.But I don't know how to do.Have any good suggestion to me?Thanks.

let string = "hello\nNice to meet you.\nMy name is Leo.\n" //I want to get 3

Upvotes: 0

Views: 210

Answers (2)

vadian
vadian

Reputation: 285160

An alternative is to split the lines with the components(separatedBy method:

let string = "hello\nNice to meet you.\nMy name is Leo.\n"
let lineCounter = string.components(separatedBy: "\n").count - 1

or more versatile to consider all kinds of newline characters

let lineCounter = string.components(separatedBy: CharacterSet.newlines).count - 1

Due to the trailing newline character the result is 4. To ignore a trailing new line you have to decrement the result.

Upvotes: 0

rmaddy
rmaddy

Reputation: 318854

If you simply want a count of newline characters then you can use a filter on the string's characters:

let string = "hello\nNice to meet you.\nMy name is Leo.\n"
let count = string.characters.filter { $0 == "\n" }.count
print(count)

This outputs 3 as expected.

Upvotes: 1

Related Questions