nail fei
nail fei

Reputation: 2329

golang with compile error: undefined: strings in strings.trim

I try to use golang deal with this problem 557. Reverse Words in a String III my code as below:

import "fmt"
import  ss "strings"

func reverseWords(s string) string {
    words := ss.Split(s," ");
    res := "";
    for i:=0; i < len(words);i++{
        curWord := ss.Split(words[i],"");
        for j:=len(curWord)-1; j >= 0;j--{
            res += curWord[j];
        }
        if(i!=len(words)-1){
            res += " ";
        }
    }
    return res;
}

func main(){
    s := "Let's take LeetCode contest";
    fmt.Println(reverseWords(s));
}

Everything is ok in my pc, it can pass compile at least.
However, when I submit in leetcode it tell me :

 Line 67: undefined: strings in strings.Trim 

I google this error but get nothing relevant info. As a beginner in golang, I need help. Everything will be appreciated.

Upvotes: 8

Views: 16257

Answers (2)

Adrian
Adrian

Reputation: 46602

You're importing strings under an alias:

import  ss "strings"

That means that everywhere in that file, instead of referring to strings you must refer to ss, for example:

words := ss.Split(s," ")

If you use the default import:

import "strings"

Then you can refer to it as strings as normal.

Note that the currently accepted answer is wrong about two things: you can absolutely use the alias as you have it, you just have to refer to the package with the aliased name. It will not cause any issues if you use the name you gave it. Second, you absolutely do need to import the strings package - with or without an alias, your choice - if you want to refer to it.

On a completely unrelated side note, you should strongly consider running go fmt on your code, as it does not follow Go coding standards; for example, standard Go code omits the vast majority of semicolons. The code will work regardless, but you'll have an easier time getting help from other Go developers if your code is formatted the way everyone else is used to seeing it.

Upvotes: 7

Abhilekh Singh
Abhilekh Singh

Reputation: 2963

If you import strings package with different name then it will cause issue as it is used by the wrapper code to run the function completely.

No need to import strings package again. It will be added.

Just use it directly.

func reverseWords(s string) string {
    words := strings.Split(s," ");
    res := "";
    for i:=0; i < len(words);i++{
        curWord := strings.Split(words[i],"");
        for j:=len(curWord)-1; j >= 0;j--{
            res += curWord[j];
        }
        if(i!=len(words)-1){
            res += " ";
        }
    }
    return res;
}

Upvotes: 0

Related Questions