Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace characters in Swift String? [duplicate]

Tags:

swift

I have a string that contains a comma. However, I would like to replace the comma by a point. This must be possible unfortunately I can not get it done. I'm not just getting back the .5. The comma is away only everything that stonged for it unfortunately too.

let cijfers = "38,5"
let start = cijfers.startIndex;
let end = cijfers.index(cijfers.startIndex, offsetBy: 3);
let result = cijfers.replacingCharacters(in: start..<end, with: ".")
print(result)
like image 956
André Avatar asked Sep 21 '18 01:09

André


People also ask

How do I remove a specific character from a string in Swift?

Removing the specific character To remove the specific character from a string, we can use the built-in remove() method in Swift. The remove() method takes the character position as an argument and removed it from the string.

What is string interpolation in Swift?

String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. You can use string interpolation in both single-line and multiline string literals.

How do I change the last character of a string in Swift?

To remove the last character of a string, we can use the built-in removeLast() method in Swift. Note: The removeLast() method modifies the original string.


1 Answers

You use cijfers.replacingOccurrences not on the correct way, for your purpose. Try this:

let str = "38,5"
let replaced = str.replacingOccurrences(of: ",", with: ".")
print(replaced)
like image 136
Wouter Avatar answered Oct 21 '22 10:10

Wouter