struggling_learner
struggling_learner

Reputation: 1258

go replace a char literal in a string

In golang, what's the easiest way to replace a char literal in a string?

Here's the C code, where we replace the whitespace with '3':

#include <stdio.h>
#include <string.h>

int main(){

    char input[] = "Look ma no hands";
    printf("Input \"%s\" ", input);
    for (int i = 0; i < strlen(input); i++){
        //printf("input[%d] is %c\n", i, input[i]);
        if ( input[i] == ' ' ){
            input[i] = 3;
        }
    }

    printf(",converted to :%s\n", input);
    return 0;
}

The output:

$ ./a.out 
Input "Look ma no hands" ,converted to :Lookmanohands

How can we do this in golang?

Upvotes: 1

Views: 481

Answers (1)

filipe
filipe

Reputation: 2047

This is the the nearest of the c example I could make:

func main() {
    input := "Look ma no hands"

    var b strings.Builder
    b.Grow(len(input))
    for _, p := range input[:] {
        if p == ' '{
            fmt.Fprintf(&b, "%c", '3')
        }else{
            fmt.Fprintf(&b, "%c", p)
        }
    }
    s := b.String()
    fmt.Println(s)
}

But as you can see, we can't modify the original string so we are not "replacing" in original string but creating a new string.

Upvotes: 2

Related Questions