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?
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)
}
}
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
Related
I referred this SO post to remove whitespaces and newline characters from a string. But in my string, I may have extra whitespaces as well as extra newline characters. I want to remove the unnecessary \n's and whitespaces from that string.
But if there is a string like so..."This \n is a st\tri\rng" then I don't want Thisisastring as the result but instead something like this..
This is a string
To replace contiguous spaces with a single space, replace Regular Expression \s+ with a single space:
let str = "This \n\n is a string"
if let regex = try? NSRegularExpression(pattern: "\\s+", options: NSRegularExpression.Options.caseInsensitive)
{
let result = regex.stringByReplacingMatches(in: str, options: [], range: NSMakeRange(0, str.count), withTemplate: " ")
print(result) //output: "This is a string"
}
I'm trying to replace some HTML codes in Swift with the appropriate characters. I used a String extension.
extension String {
mutating func fix_HTML_Codes() {
let originalString = self
let newString = originalString.replacingOccurrences(of: "'", with: "\'")
let newString2 = newString.replacingOccurrences(of: """, with: "\"")
self = newString2
}
}
However, instead of replacing my escaped single quote with a single quote, it actually replaces it with \', anyone know why?
Here's an example of what I'm getting:
"On which Beatles album would you find the song \'Eleanor Rigby\'?"
It's including the escape character.
Sorry if the title is not clear.
What I mean is this:
If I have a variable, we'll call that a, with a value of "Hello\nWorld", it would be written as
var a = "Hello\nWorld
And if I were to print it, I'd get
Hello
World
How could I print it as:
Hello\nWorld
I know this is a little old however I was looking for a solution to the same problem and I figured out something easy.
If you're wanting to print out a string that shows the escape characters like "\nThis Thing\nAlso this"
print(myString.debugDescription)
Here's a more complete version of #Pedro Castilho's answer.
import Foundation
extension String {
static let escapeSequences = [
(original: "\0", escaped: "\\0"),
(original: "\\", escaped: "\\\\"),
(original: "\t", escaped: "\\t"),
(original: "\n", escaped: "\\n"),
(original: "\r", escaped: "\\r"),
(original: "\"", escaped: "\\\""),
(original: "\'", escaped: "\\'"),
]
mutating func literalize() {
self = self.literalized()
}
func literalized() -> String {
return String.escapeSequences.reduce(self) { string, seq in
string.replacingOccurrences(of: seq.original, with: seq.escaped)
}
}
}
let a = "Hello\0\\\t\n\r\"\'World"
print("Original: \(a)\r\n\r\n\r\n")
print("Literalized: \(a.literalized())")
You can't, not without changing the string itself. The \n character sequence only exists in your code as a representation of a newline character, the compiler will change it into an actual newline.
In other words, the issue here is that the "raw" string is the string with the actual newline.
If you want it to appear as an actual \n, you'll need to escape the backslash. (Change it into \\n)
You could also use the following function to automate this:
func literalize(_ string: String) -> String {
return string.replacingOccurrences(of: "\n", with: "\\n")
.replacingOccurrences(of: "\t", with: "\\t")
}
And so on. You can add more replacingOccurrences calls for every escape sequence you want to literalize.
If "Hello\nWorld" is literally the string you're trying to print, then all you do is this:
var str = "Hello\\nWorld"
print(str)
I tested this in the Swift Playgrounds!
Late to the party but the answer to this question is to map the String UnicodeScalarView Unicode.Scalar elements converting them to escaped ascii strings. Then you can simply join back the string:
extension Unicode.Scalar {
var asciiEscaped: String { escaped(asASCII: true) }
}
extension StringProtocol {
var asciiEscaped: String {
unicodeScalars.map(\.asciiEscaped).joined()
}
}
print("Hello\nWorld".asciiEscaped) // Hello\nWorld
Just use double \
var a = "Hello\\nWorld"
I have multiple lines in an String, for example:
let str = "Mieter: Hannes Tester \nVerwalter: Michael Karner \n"
Now i want to remove the whole sentence between "Mieter" and the line break. So the result should be:
let str = "Verwalter: Michael Karner \n"
I could check with Regex, but i am only able to get the string between 2 words. For example with:
if let match = str.rangeOfString("(?<=Mieter)[^\n]+", options: .RegularExpressionSearch) {
print(str.substringWithRange(match)) // between
}
But how can i replace a whole line?
Edit:
It is not working anymore when its between a string:
let str = "Test \n Mieter: \n Hausverwalter: \n Firma: \n"
str.stringByReplacingOccurrencesOfString("^Mieter[^\n]+\\s", withString: "", options: .RegularExpressionSearch, range: nil)
// so "Mieter \n" is not being replaced.
Use replacingOccurrencesOf
let str = "Mieter: Hannes Tester \nVerwalter: Michael Karner \n"
str.replacingOccurrences(of: "^Mieter[^\n]+\\s", with: "", options: .regularExpression)
This is Swift 3 code
Edit:
If the substring is not at the beginning of the string remove the leading caret (^).
While I was trying to use Swift's String(format: format, args) method, I found out that I cannot print the formatted string directly without newline(\n) and brackets being added.
So for example, I have a code like this:
func someFunc(string: String...) {
print(String(format: "test %#", string))
}
let string = "string1"
someFunc(string, "string2")
the result would be:
"test (\n string1,\n string2\n)\n"
However, I intend to deliver the result like this:
"test string1 string2"
How can I make the brackets and \n not being printed?
Since string parameter is a sequence, you can use joinWithSeparator on it, like this:
func someFunc(string: String...) {
print(string.joinWithSeparator(" "))
}
someFunc("quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog")
You will first need to concatenate your list of input strings, otherwise it will print as a list, hence the commas and parentheses. You can additionally strip out the newline characters and whitespace from the ends of the string using a character set.
var stringConcat : String = ''
for stringEntry in string {
stringConcat += stringEntry.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
Then just print out the stringConcat.