Print String using variadic params without comma, newline and brackets in Swift - swift

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.

Related

Disregard letter when finding substring - Swift

How do you make a letter count as another when finding a substring in Swift? For example, I have a string:
I like to eat apples
But I want to be able to make it where all instances of 'p' could be written as 'b'.
If the user searches "abbles", it should still return the substring "apples" from the quote. I have this issue because I want whenever a user searches
اكل
But the quote contains
أكل
it would return that value. I tried fullString.range(of: string, options: [.diacriticInsensitive, .caseInsensitive] but this does not fix it since the "ء" are not diacritics, so أ إ ا all behave differently when they should all be the same. Users only use ا. How do I make it count for أ and إ without replacing all instances of them with ا?
You could add a small String extension that uses simple regular expressions (as matt suggested in the comments) to do the actual matching. Like so:
extension String {
func contains(substring: String, disregarding: [String]) -> Bool {
var escapedPattern = NSRegularExpression.escapedPattern(for: substring)
for string in disregarding {
let replacement = String(repeating: ".", count: string.count)
escapedPattern = escapedPattern.replacingOccurrences(of: string, with: replacement)
}
let regEx = ".*" + escapedPattern + ".*"
return self.range(of: regEx,
options: .regularExpression) != nil
}
}
Example output:
"I like apples".contains(substring: "apples", disregarding: ["p"]) //true
"I like abbles".contains(substring: "apples", disregarding: ["p"]) //true
"I like oranges".contains(substring: "apples", disregarding: ["p"]) //false

Swift string comparison failure due to newlines

I am trying to compare two strings
1. String read from a .strings file using the api, String(contentsOf: localizableFilePath, encoding: .ascii).propertyListFromStringsFileFormat()
2. Strings to be written to the strings file
The string comparison fails when there are newlines in the strings, i,e
the string 1 has newLine character in them so its like
"something
something"
and string 2 is like "something \nsomething"
and the comparison fails because of this.
You can try replacing occurrences of newline characters with an empty string: For example:
let inputString = "Something \nSomething"
let test = "Something Something"
test == inputString.replacingOccurrences(of: "\n", with: "") // true

Swift NSAlert() argument print string with spaces

How do a print the array below to display the full string?
alert.informativeText = CommandLine.arguments[4]
This prints fine if it's one word. Argument Test
Test
However if the argument is This Is A Test. It still prints just the first word:
Test
Full Code:
CommandLine.arguments[1]{
func dialogOKCancel(title: String) -> Bool
{
let alert = NSAlert()
alert.informativeText = CommandLine.arguments[4]
alert.alertStyle = NSAlert.Style.warning
alert.addButton(withTitle: "Dismiss")
return alert.runModal() == NSApplication.ModalResponse.alertFirstButtonReturn
}
_ = dialogOKCancel(title: "")
The space character is the argument separator in the command line.
You have to quote the string
/path/to/executable 'This is A Test'
or to escape
/path/to/executable This\ is\ A\ Test
the spaces in the string when calling the executable.
Command line arguments are always split with spaces. Although "This Is A Test" might look like a single argument, it is four arguments - "This", "Is", "A" and "Test".
What you are trying to do seems to be printing all the arguments. In that case, you should drop the first element of CommandLine.arguments (that's the command itself) and then join the strings:
alert.informativeText = CommandLine.arguments.dropFirst().joined(separator: " ")

How to print Escape Sequence characters in Swift?

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"

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?
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