判断字符串在特定位置是否有数字

Find out if a string has a number in a specific position

是否可以有一个字符串,例如:

var myText = "AB12CDE"

然后检查第 3 个和第 4 个字母是否为数字,如果不是,则将其更改为数字。

所以如果上面的文字最终是:

"ABIZCDE" 

我可以将 IZ 更改为 12,但不能替换 I 和 Z 的所有实例,而只能替换第 3 个和第 4 个字符。

您可以尝试这样的操作:

首先,从位置 2 到下一个 2 点的范围内找到字符串的子字符串,然后检查它是否是整数。如果不是,则将其替换为整数。

var myText = "ABIZCDE"

        let myNSString = myText as NSString
        let subString = myNSString.substring(with: NSRange(location: 2, length: 2))

        print(subString)

        let isInt = Int(subString) != nil
        if !isInt {
            myNSString.replacingCharacters(in: NSRange(location: 2, length: 2), with: "12")
        }

        print(myNSString)

希望对您有所帮助!!

这是它:

let str = "ABCIZCDEZ"
var newString = ""
var index = 0
str.forEach { (char) in            
    var charToAppend = char
    if index == 3 || index == 4 {
        if char == "Z" {
            charToAppend = "2"
        }
        if char == "I" {
            charToAppend = "1"
        }
    }
    newString.append(charToAppend)
    index += 1
}

print(newString) // ABC12CDEZ

例如,对于插入,您可以进行扩展:

在你的 class:

之前的某处添加这个
public extension String {
    public func insert(string: String, index: Int) -> String {
        return String(self.prefix(index)) + string + String(self.suffix(self.count - index))
    }
}

然后:

let str2 = "ABC2CDEZ"
var newString = str2.insert(string: "I", index: 3)
print(newString) // ABCI2CDEZ

可能有更简单的替代方案,但以下方案可行:

let myText = "ABIZCDEIZIZ"

let result = myText
    // replace any I at 3rd or 4th position with 1
    .replacingOccurrences(of: "(?<=^.{2,3})I", with: "1", options: .regularExpression)
    // replace any Z at 3rd or 4th position with 2
    .replacingOccurrences(of: "(?<=^.{2,3})Z", with: "2", options: .regularExpression)
print(result) // AB12CDEIZIZ

或者,没有正则表达式:

let result = String(myText.enumerated().map {
    guard (2...3).contains([=11=].offset) else { return [=11=].element }

    switch [=11=].element {
    case "I":
        return "1"
    case "Z":
        return "2"
    default:
        return [=11=].element
    }
})

print(result)

或一起移动逻辑:

let result = String(myText.enumerated().map {
    switch [=12=].element {
    case "I" where (2...3).contains([=12=].offset):
        return "1"
    case "Z" where (2...3).contains([=12=].offset):
        return "2"
    default:
        return [=12=].element
    }
})

所以我在操场上模拟了一些可以达到预期效果的东西,它的额外好处是能够定义任意数量的替换规则:

import Foundation

struct Substitution {

    var origin: String
    var result: String
    var targetIndices: [Int]
}

let subs = [
    Substitution(origin: "1", result: "I", targetIndices:[2, 3]),
    Substitution(origin: "2", result: "Z", targetIndices:[2, 3])
]

let charset = CharacterSet(charactersIn: subs.map({ [=10=].origin }).joined(separator: ""))

let input = "AB12CDE"

func process(_ input: String) -> String {

    var output = input

    for (index, character) in input.enumerated() {
        if let sub = subs.first(where: { [=10=].targetIndices.contains(index) && [=10=].origin == String(character) }) {
            output = (output as NSString).replacingCharacters(in: NSMakeRange(index, 1), with: sub.result)
        }
    }

    return output
}

let output = process(input)
var str = "AB12CDE"
    let index1 = str.index (str.startIndex, offsetBy: 2)
    let index2 = str.index (str.startIndex, offsetBy: 3)
    print(str[index1],str[index2])
    if str[index1] == "1" && str[index2] == "2" {
        let newString = str.prefix(2) + "IZ" + str.dropFirst(5)
        print(newString)
    }

你可以试试这个。

这列举了一个详尽的字符列表,您可能想用字母替换,您可以添加更多:

extension Character {
    var alpabetNumber: Character? {
        switch self {
        case "I":
            return "1"
        case "Z":
            return "2"
        default:
            return nil
        }
    }
}

完成这项工作的函数:

extension String {
    mutating func namePlate() -> String {
        var index = 0
        self.forEach { (char) in
            if index == 2 || index == 3 {
                if let replacement = char.alpabetNumber {
                    self = replace(self, index, replacement)
                }
            }
            index += 1
        }
        return self
    }
}

// Helper
func replace(_ myString: String, _ index: Int, _ newChar: Character) -> String {
    var modifiedString = String()
    for (i, char) in myString.enumerated() {
        modifiedString += String((i == index) ? newChar : char)
    }
    return modifiedString
}

用法:

var str = "ABIZCDE"
str.namePlate() // "AB12CDE"