Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last punctuation of a swift string

I'm trying to remove the last punctuation of a string in swift 2.0

var str: String = "This is a string, but i need to remove this comma,      \n"
var trimmedstr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

First I'm removing the the white spaces and newline characters at the end, and then I need to check of the last character of trimmedstr if it is a punctuation. It can be a period, comma, dash, etc, and if it is i need to remove it it.

How can i accomplish this?

like image 213
Vitalik K Avatar asked Jan 06 '23 22:01

Vitalik K


2 Answers

There are multiple ways to do it. You can use contains to check if the last character is in the set of expected characters, and use dropLast() on the String to construct a new string without the last character:

let str = "This is a string, but i need to remove this comma, \n"

let trimmedstr = str.trimmingCharacters(in: .whitespacesAndNewlines)

if let lastchar = trimmedstr.last {
    if [",", ".", "-", "?"].contains(lastchar) {
        let newstr = String(trimmedstr.dropLast())
        print(newstr)
    }
}
like image 152
vacawama Avatar answered Jan 11 '23 17:01

vacawama


Could use .trimmingCharacters(in:.whitespacesAndNewlines) and .trimmingCharacters(in: .punctuationCharacters)

for example, to remove whitespaces and punctuations on both ends of the String-

let str = "\n This is a string, but i need to remove this comma and whitespaces, \t\n"

let trimmedStr = str.trimmingCharacters(in: .whitespacesAndNewlines).trimmingCharacters(in: .punctuationCharacters)

Result -

This is a string, but i need to remove this comma and whitespaces

like image 38
anoo_radha Avatar answered Jan 11 '23 17:01

anoo_radha