stringByReplacingOccurrencesOfString删除整个字符串

时间:2016-02-03 17:08:37

标签: swift nsstring

我试图将字符串写入文本框,但如果第一个字符是*或字符串==""我不想写字符串。但我想删除所有空格来执行此操作

for command in InitialCommandsArr {
    let nulledCommand = command.stringByReplacingOccurrencesOfString(" ", withString: "")

    if nulledCommand != "" && 
       command.stringByReplacingOccurrencesOfString(" ", withString: "").characters.first != "*"
    {
        OutputCommand.text = "\(OutputCommand.text),{id:\"MinecartCommandBlock\",Command:\(command)}}"
    }
}

当我这样做的时候用#34替换了整个字符串;"帮助

1 个答案:

答案 0 :(得分:1)

试过这个:

    var labelText = "";
    let initialCommandsArr = ["foo","bar","*baz","   "]

    for command in initialCommandsArr {
        let nulledCommand = command.stringByReplacingOccurrencesOfString(" ", withString: "")
        if(nulledCommand.characters.count > 0 && nulledCommand.characters.first != "*"){

            labelText += ",{id:\"MinecartCommandBlock\",Command: \(command) }}"
        }
    }

    print(labelText)

打印出来:

,{id:"MinecartCommandBlock",Command: foo }},{id:"MinecartCommandBlock",Command: bar }}

那就是你想要的?