ios - 用不同的文本长度替换字符串中不同长度的数字

标签 ios string swift2 nsscanner

问题:数字的长度不同,可能是 1、200、1000、39 99995 等。需要用文本替换,例如。与数值不同长度比较的“Apple”。

let str: String = "hello i have 1313 object of 10 string class with 1 object, similar to 9999 errors"

预期结果 = "你好我有 Apple 字符串类的 Apple 对象和 Apple 对象,类似于 Apple 错误”

我试过下面的代码:

 var originalString: String = "hello i have 1313 object of 10 string class with 1 object, similar to 9999 errors"

    let strippedString: NSMutableString = NSMutableString(capacity: originalString.characters.count)
    var numArray: [String] = []
    var locArray: [NSNumber] = []
    var scanner: NSScanner = NSScanner(string:originalString)
    let numbers: NSCharacterSet = NSCharacterSet(charactersInString: "0123456789")
    while scanner.atEnd == false {
        var buffer: NSString?
        if scanner.scanCharactersFromSet(numbers, intoString: &buffer) {
            strippedString.appendString(buffer! as String)
            numArray.append(buffer! as String)
            locArray.append(scanner.scanLocation)
        }
        else {

            scanner.scanLocation = (scanner.scanLocation + 1)
        }
    }
    for (index, _) in numArray.enumerate() {
        var loc : Int = Int(locArray[index] ) - (String(numArray[index]).characters.count)
        let len = String(numArray[index]).characters.count
        let dupStr = "Apple"
        if(index != 0 && len !=  dupStr.characters.count)
        {
            loc = loc + (dupStr.characters.count - len) + 1
        }
        originalString.replaceRange(originalString.startIndex.advancedBy(loc)..<originalString.startIndex.advancedBy(loc + len), with: dupStr)
    }
    print(originalString)

最佳答案

swift 2

NSScanner 很棒,但是如果您想要一个更简单的解决方案来完成此任务,您可以使用 componentsSeparatedByStringmapInt()joinWithSeparator,像这样:

let originalString = "hello i have 1313 object of 10 string class with 1 object, similar to 9999 errors"
let tokens = originalString.componentsSeparatedByString(" ")
let newTokens = tokens.map { (token) -> String in
    if let _ = Int(token) {
        return "Apple"
    }
    return token
}
let result = newTokens.joinWithSeparator(" ")
print(result)

打印:

hello i have Apple object of Apple string class with Apple object, similar to Apple errors

还有一个简短的映射版本:

let newTokens = tokens.map { Int($0) != nil ? "Apple" : $0 }

swift 3

componentsSeparatedByString(_:) 现在是 components(separatedBy:)joinWithSeparator(_:) 现在是 joined(分隔符:).

let tokens = originalString.components(separatedBy: " ")
let newTokens = tokens.map { Int($0) != nil ? "Apple" : $0 }
let result = newTokens.joined(separator: " ")

关于ios - 用不同的文本长度替换字符串中不同长度的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37436587/

相关文章:

ios - 在 UIWebview,iOS 中自动播放视频

ios - 快速检测不透明空间的两个节点之间接触的方法?

c - 带大括号的字符串初始值设定项

ios - 基本开关错误

swift - 设置数据源和委托(delegate)会使 UITableView 的应用程序崩溃

ios - 如何继续下一个viewController

javascript - DOM 就绪的 iOS UIWebView

iOS 应用程序登录网站

c - 一次读取文件而不是逐行读取文件(在 c 中)

string - 如何在 CSV 文件末尾多次添加相同的字符串?