从Swift字符串中删除2个字符

时间:2015-07-28 00:44:40

标签: string swift nsstring

编辑:我解决了,我需要切换两个值。感谢你们。现在我唯一的问题是,我想删除从HI到*(类名的指针)的所有内容。 如何在此处添加范围以去除HI和&之间的所有内容在Swift的String中?

我通常倾向于通过类似于此的调用从Swift中的字符串中删除字符:

textToConvert = inputField.stringValue.stringByReplacingOccurrencesOfString("&", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

现在,输出符合预期。字符串中的所有“&”都将被删除。但是,当我尝试使用2个字符时,例如:

textToConvert = inputField.stringValue.stringByReplacingOccurrencesOfString("HI", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

没有骰子,这两个字符永远不会从字符串中删除。这很奇怪。有谁知道为什么会这样?

编辑:这是整个功能(固定版本):

@IBAction func saySomethingPressed(sender: AnyObject) {

        var textToConvert = inputField.stringValue

        if (textToConvert == "Hello" || textToConvert == "hello" || textToConvert == "hey"){
                responseLabel.stringValue = "Well hello there!"
        }

        else {


        textToConvert = inputField.stringValue.stringByReplacingOccurrencesOfString("HI", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

         textToConvert = textToConvert.stringByReplacingOccurrencesOfString("&", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

        responseLabel.stringValue = textToConvert

        }
    }
}

1 个答案:

答案 0 :(得分:1)

为了完整性:

 textToConvert = inputField.stringValue.stringByReplacingOccurrencesOfString("HI", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

     textToConvert = textToConvert.stringByReplacingOccurrencesOfString("&", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

正在重新分配textToConvert变量。