0

I want to create a function that will replace every dot with a comma in a provided string.
My code looks like this:

public void replaceDot(ref string str) {
            for(int i = 0; i < str.Length; i++) {
                if (str[i] == '.') {
                    str[i] = ',';     //readonly error here
                }
            }
        }

Any ideas how to make it work? I also tried using foreach loop but it also didn't work.

czarson
  • 125
  • 7
  • 7
    how about using `string.Replace()` (https://learn.microsoft.com/de-de/dotnet/api/system.string.replace?view=net-5.0)? – fubo Jan 20 '21 at 13:33
  • i'll look into it – czarson Jan 20 '21 at 13:34
  • Why have you written this code? Do you realise strings are read-only (unless you want to go and do nasty, unsafe things)? What's wrong with `string.Replace()`? – CodeCaster Jan 20 '21 at 13:36
  • I've written this code because i have a Windows Forms application in which i convert text from textboxes to floating-point values and it throws an error if the text is written as for example "32.45", it only works when there's a comma instead of a dot. Also, nothing is wrong with string.Replace(), I didnt know that this function exists as i'm a beginner. – czarson Jan 20 '21 at 13:41
  • But you can pass a culture to `float.TryParse()` to allow a culture that has dots as decimal separator, or comma, whichever you want. Anyhow see duplicates. :) – CodeCaster Jan 20 '21 at 13:50

0 Answers0