상세 컨텐츠

본문 제목

[Go] Array and string - Immutable String - Problems & Solutions

Go/Leet Code

by Gopythor 2022. 4. 2. 17:56

본문

728x90
반응형

Beware of String Concatenation in Java

Code

Java

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
        String s = "";
        int n = 10000;
        for (int i = 0; i < n; i++) {
            s += "hello";
        }
    }
}

Go

func main() {
	var s string = ""
	var n int = 10000
	for i := 0; i < n; i++ {
		s += "hello"
	}
}

https://go.dev/play/p/08cAfn65srV

Solution

Code(Convert to a array)

Java

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
        String s = "Hello World";
        char[] str = s.toCharArray();
        str[5] = ',';
        System.out.println(str);
    }
}

Go

func main() {
	var s string = "Hello World"
	str := []rune(s)
	str[5] = ','
	fmt.Println(s)
}

https://go.dev/play/p/F584GNYCUt2

 

Go Playground - The Go Programming Language

About the Playground The Go Playground is a web service that runs on go.dev's servers. The service receives a Go program, vets, compiles, links, and runs the program inside a sandbox, then returns the output. If the program contains tests or examples and n

go.dev

 

Code(StringBuilder)

Java

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
        int n = 10000;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < n; i++) {
            str.append("hello");
        }
        String s = str.toString();
    }
}

Go

func main() {
	var n int = 10000
	var sb strings.Builder
	for i := 0; i < n; i++ {
		sb.WriteString("hello")
	}
	var s string = sb.String()
	fmt.Println(s)
}

https://go.dev/play/p/j48LhNoSo_Y

728x90
반응형

관련글 더보기

댓글 영역