Is there a way to generate a random string with a particular pattern? e.g. ar5-Edg-2ah
1 Like
@rufy You should create a random string generator in this case like this:
class RandomString {
// 1
private let parts: Int
private var strings: [String] = []
private enum CharacterType: Int {
case digit, upper, lower
}
// 2
init(parts: Int = Int.random(in: 1...10)) {
self.parts = parts
create()
}
// 3
private func create() {
for _ in 1...parts {
let part = Int.random(in: 1...10)
let string = createString(part)
strings.append(string)
}
}
// 4
private func createString(_ part: Int) -> String {
var string = ""
for _ in 1...part {
let character = createCharacter()
string.append(character)
}
return string
}
// 5
private func createCharacter() -> Character {
let type = Int.random(in: 0...2)
let characterType = CharacterType(rawValue: type)!
switch characterType {
case .digit: return getCharacter(48, 57)
case .upper: return getCharacter(65, 90)
case .lower: return getCharacter(97, 122)
}
}
// 6
private func getCharacter(_ lower: Int, _ upper: Int) -> Character {
let value = Int.random(in: lower...upper)
let scalar = Unicode.Scalar(value)!
return Character(scalar)
}
// 7
func format(with separator: String = "-") -> String {
strings.joined(separator: separator)
}
}
There is quite a lot going on over here, so breaking it into steps:
- Define the number of substrings and the type of characters in the final string.
- Use random numbers to generate the number of substrings in the final string.
- Use random numbers to generate the number of characters in the substrings and append the substrings to the final string.
- Create the substrings by appending their characters.
- Use random numbers to determine the type of the characters in the substrings and create the characters in the substrings.
- Get the specific character from its corresponding Unicode scalar.
- Get the final string by joining its substrings.
This is how you use the random string generator:
let randomString = RandomString()
let string = randomString.format()
print(string)
Please let me know if you have any questions or issues about the whole thing when you get a chance. Thank you!
1 Like
This topic was automatically closed after 166 days. New replies are no longer allowed.