Como comparar num if strings

In Go language, the string is an immutable chain of arbitrary bytes encoded with UTF-8 encoding. You are allowed to compare strings with each other using two different ways:

1. Using comparison operators: Go strings support comparison operators, i.e, ==, !=, >=, <=, <, >. Here, the == and != operator are used to check if the given strings are equal or not, and >=, <=, <, > operators are used to find the lexical order. The results of these operators are of Boolean type, meaning if the condition is satisfied it will return true, otherwise, return false.

Example 1: 

    fmt.Println("Result 1: ", result1)

    fmt.Println("Result 2: ", result2)

    fmt.Println("Result 3: ", result3)

    fmt.Println("Result 4: ", result4)

    fmt.Println("\nResult 5: ", result5)

    fmt.Println("Result 6: ", result6)

    fmt.Println("Result 7: ", result7)

    fmt.Println("Result 8: ", result8)

Output: 

Result 1: false Result 2: false Result 3: false Result 4: true Result 5: true Result 6: true Result 7: true Result 8: false

Example 2: 

    myslice := []string{"Geeks", "Geeks",

    fmt.Println("Slice: ", myslice)

    result1 := "GFG" > "Geeks"

    fmt.Println("Result 1: ", result1)

    result2 := "GFG" < "Geeks"

    fmt.Println("Result 2: ", result2)

    result3 := "Geeks" >= "for"

    fmt.Println("Result 3: ", result3)

    result4 := "Geeks" <= "for"

    fmt.Println("Result 4: ", result4)

    result5 := "Geeks" == "Geeks"

    fmt.Println("Result 5: ", result5)

    result6 := "Geeks" != "for"

    fmt.Println("Result 6: ", result6)

Output: 

Slice: [Geeks Geeks gfg GFG for] Result 1: false Result 2: true Result 3: false Result 4: true Result 5: true Result 6: true

2. Using Compare() method: You can also compare two strings using the built-in function Compare() provided by the strings package. This function returns an integer value after comparing two strings lexicographically. The return values are: 

  • Return 0, if str1 == str2.
  • Return 1, if str1 > str2.
  • Return -1, if str1 < str2.

Syntax: 

func Compare(str1, str2 string) int

Example:

    fmt.Println(strings.Compare("gfg", "Geeks"))

    fmt.Println(strings.Compare("GeeksforGeeks",

    fmt.Println(strings.Compare("Geeks", " GFG"))

    fmt.Println(strings.Compare("GeeKS", "GeeKs"))

Output: 

1 0 1 -1

Article Tags :

Comparar o tamanho de strings é uma função comum na programação da linguagem C, pois ela permite verificar qual delas contém mais caracteres. Tal recurso é muito útil para ordenar dados. Comparar strings requer uma função especial; não use != ou ==.

  1. 1

    Na linguagem C, existem duas funções que permitem comparar strings. Ambas as funções fazem parte da biblioteca <string.h>.

    • strcmp() : Essa função compara duas strings e retorna a diferença no número de caracteres.
    • strncmp() : Semelhante à função strcmp(), exceto que esta compara os n primeiros caracteres das strings. Ela é considerada uma função mais segura, pois ajuda a evitar que ocorra overflow.

  2. 2

    Inicie o programa com as bibliotecas necessárias. Você vai precisar das bibliotecas <stdio.h> e <string.h>, juntamente com todas as outras bibliotecas necessárias para o programa.

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

  3. 3

    Inicie com a função .int. Esta é a forma mais fácil de aprender a função, já que ela retornará um valor inteiro que compara o tamanho das duas strings.

    #include <stdio.h> #include <string.h> int main () { }

  4. 4

    Defina as duas strings que você deseja comparar. Para este exemplo, iremos comparar duas strings char. Defina também o valor retornado como um inteiro.[1] X Fonte de pesquisa Ir à fonte

    #include <stdio.h> #include <string.h> int main () { char *str1 = "melancia"; char *str2 = "laranja"; int ret; }

  5. 5

    Inclua a função escolhida. Agora que você tem as duas strings definidas, adicione a função para compará-las. Neste exemplo, usaremos strncmp(), portanto devemos definir na função o número de caracteres que serão comparados.

    #include <stdio.h> #include <string.h> int main () { char *str1 = "melancia"; char *str2 = "laranja"; int ret; ret = strncmp(str1, str2, 6); /*Aqui, a função irá comparar os 6 primeiros caracteres */ }

  6. 6

    Use a estrutura .if...else para fazer a comparação. Depois de incluir a função no seu código, use a estrutura if...else para exibir qual das duas strings é maior. A função strncmp() retornará o valor 0 se as strings tiverem o mesmo comprimento, um número positivo se str1 for maior e um número negativo se str2 for maior.

    #include <stdio.h> #include <string.h> int main () { char *str1 = "melancia"; char *str2 = "laranja"; int ret; ret = strncmp(str1, str2, 6); if(ret > 0) { printf("str1 é maior"); } else if(ret < 0) { printf("str2 é maior"); } else { printf("As duas palavras são iguais"); } return(0); }

  • Lembre-se de que, se as strings forem iguais, o valor retornado será 0. Isso pode confundir, já que esse valor numérico também representa o valor lógico FALSE.