Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
For a given String in Swift I need to remove prefix and suffix characters that belong to a predefined character set.
I can use components(separatedBy:) with the character set and get rid of the empty strings at the beginning and end of the components array. Just wondering if there's a better approach?
Thanks!
You can use .trimmingCharacters(in: CharacterSet) on the string. From the 'help' text in Xcode on this function: "Returns a new string made by removing from both ends of the String characters contained in a given character set."
Here is a unit test example using a custom character set. Notice it only removes characters from the start and end, not the middle (the comma stays):
import XCTest
class TrimCharacters: XCTestCase {
func testExample() throws {
let string = "abcbaHello, World!ccbbaa"
let charactersToTrim = CharacterSet(charactersIn: "abc,")
XCTAssertEqual(string.trimmingCharacters(in: charactersToTrim), "Hello, World!")
}
}
There are also predefined character sets that can be useful. You can also invert a character set. See CharacterSet
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have implemented an quiz application in swift 4.0. Here, user can enter his choice from ("one" or "1") to ("four" or "4") .
If the user can provide his choice as an integer(Eg 1,2,3, or 4)then there is no issue.
but if he provide his choice as an alphabet characters (Eg "one","two", ..), then i am facing the issues while validating correct answer.
Kindly, could anyone help me, How to convert word characters "one" into integer 1 etc..
thanks a lot in advance.
You can use NumberFormatter in this way:
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
let number = formatter.number(from: "one hundred twenty-five")
print(number) // print out 125
https://developer.apple.com/documentation/foundation/numberformatter/1408845-number
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've been using this:
if value.chars.count < value.bytes.count
puts "Some non english characters found."
end
But this incorrectly marks the following as non-English.
React and You: A Designer’s Point of View
How can I easily check if a string has no Asian/French/Russian characters?
I can probably iterate through each char in the string and if .bytes == 1 add it to a temp var. Then if that temp var is not nil it means it's an English character. But this seems rather convoluted.
As pointed out in the comments (here and here), this solution will reject some english words with letters that may be considered as "non English" characters.
Using the answer provided in "How to read only English characters" you could adjust it to remove any punctuation character or space, and make the comparison wit that same regex, something like this:
str = "React and You: A Designer’s Point of View"
str.gsub(/[[:punct:]]|\s/, "") =~ /^[a-zA-Z]+$/
#=> 0
.gsub(/[[:punct:]]|\s/, "") will remove any punctuation character or space, so you can compare that with the /^[a-zA-Z]+$/ regexp.
Here are step by step examples:
str = "React and You: A Designer’s Point of View"
str.gsub!(/[[:punct:]]|\s/, "") #=> "ReactandYouADesignersPointofView"
str =~ /^[a-zA-Z]+$/ #=> 0
str = "Comment ça va?"
str.gsub!(/[[:punct:]]|\s/, "") #=> "Commentçava"
str =~ /^[a-zA-Z]+$/ #=> nil
If you are expecting numbers too, then change the regexp to: /^[a-zA-Z0-9]+$/.
As pointed out in this comment, note that using [[:punct:]] will allow non-english punctuation characters such as ¿ or ¡; so, if those characters are also expected (and must cause to reject the sentence as valid), then maybe it is better to avoid gsub and compare to a custom regex with all allowed characters, for example1:
str =~ /^[a-zA-Z0-9\[\]{}\\*:;#$%&#?!|’'"-\.\/_\s]+$/
1 This is just an example with most common characters that i could think of, but needs to be customized with any character considered as valid.
This question already has answers here:
Generate random alphanumeric string in Swift
(24 answers)
Closed 6 years ago.
I am in the process of making one of my first apps, the aim of it is as a password generator and telling people on a scale of 1-1000 how hard it is to guess, and how hard it is to remember based on how the letters are formatted and what it looks like and how the brain remembers patterns. So far i have all the characters I want to use in an array, and I then have a for in loop that iterates through the characters, but I can't figure out how to specify the length of the password to generate, as currently it just prints each character. So, I am asking how can I make an 8 character long password generator as simply as possible, what i have so far is:
import Foundation
let chars = ["a","b","c","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u" ,"v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"]
Thank you!
var generate: String
for generate in chars {
print(generate)
}
As simply as possible use a loop and and a random number to get the character at given index:
let length = 8
var pass = ""
for _ in 0..<length {
let random = arc4random_uniform(UInt32(chars.count))
pass += chars[Int(random)]
}
print(pass)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
am working on a weather app and this question jump in my mind
original string
<span class="phrase">
string with backslash
"<span class=\"phrase\">"
You have double quotes to open and close the string. If you have a double quote halfway, the parser will think that the string ends there. Adding the backslash ('escaping' the quote) tells the parser that the quote should be interpreted as a literal quote within the string rather than a string terminator.
For more information see Swift: strings and characters (scroll down to 'Special Characters in String Literals').
The backslash is used as an escape character - a " in a string literal means 'end of the string' in Swift, so you need another character - the backslash - to tell Swift 'interpret this " literally - I want it to be part of the string.'.
Of course, in HTML you can specify the value of an attribute with a single quote as well, so
"<span class=\"phrase\">"
and
"<span class='phrase'>"
will have the same effect.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
"Rubymonk Is Pretty Brilliant".match(/ ./, 9)
How is the answer "P" calculated from this regex?
use the match method on the string
passes two arguments, a regular expression and the position in the string to begin the search.
returns the character 'P'
The criteria you posted from the Rubymonk grader answer this succinctly:
passes two arguments, a regular expression and the position in the
string to begin the search
But let's examine that in more detail. match is being passed two arguments:
/ ./, a regular expression
9, the starting position in the string
The regular expression tells us that we're looking for a space () followed by any character (.).
The starting position tells us to start at position 9 (I). So instead of applying that regex against "Rubymonk Is Pretty Brilliant", we're applying it against "Is Pretty Brilliant".
In the string "Is Pretty Brilliant", where is the first place we encounter a space followed by another character? "Is[ P]retty Brilliant", right? Thus match finds a result of P (that's space-P, matching the regex, not just P.)
To see this more clearly and to experiment further with regexes, you can try it in an irb session or in your browser using Rubular.
(Just google for RegEx + ruby, You will find explanation of regex syntax)
/ANYTHING-HERE/
Will look for ANYTHING-HERE in the text.
In Your example its (/ ./,9):
/SPACE DOT/
So it will look for space followed by single character (Dot -> single character).
9 will be "I" from the string. And that is not space, so it will go on 2 characters right. Will find space, and then will find single character "P".
That is the result.