简体   繁体   English

swift 替换第一次出现的字符串

[英]swift replace first occurrence of a String

I have the String "Das Auto ist blau, das andere ist allerdings blau"我有字符串"Das Auto ist blau, das andere ist allerdings blau"

I am trying to replace only the first "blau" with "red" .我正在尝试仅将第一个"blau"替换为"red"

I have tried it with .replacingOccurrences , but this does not work for me.我已经尝试过.replacingOccurrences ,但这对我不起作用。

You can try你可以试试

 let str = "Das Auto ist blau, das andere ist allerdings blau"
 if let range = str.range(of:"blau") {
     print(str.replacingCharacters(in: range, with:"red"))
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM