Golang Tutorial

Fundamentals

Control Statements

Functions & Methods

Structure

Arrays & Slices

String

Pointers

Interfaces

Concurrency

Check if the given characters are present in String in Golang

Checking if given characters are present in a string is a fundamental task in many programming scenarios. Let's see how you can achieve this in Go.

1. Using strings.Contains

The simplest way to check if a substring is present within a string is by using the Contains function from the strings package.

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Hello, Gophers!"

	// Check if the string contains "Goph"
	if strings.Contains(str, "Goph") {
		fmt.Println("String contains 'Goph'")
	} else {
		fmt.Println("String does not contain 'Goph'")
	}
}

2. Checking for Individual Characters

If you have multiple characters and you want to check if any of them are present in the string, you can iterate over them and use the strings.ContainsRune function.

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Hello, Gophers!"
	chars := []rune{'a', 'e', 'i', 'o', 'u'} // checking for vowels

	for _, char := range chars {
		if strings.ContainsRune(str, char) {
			fmt.Printf("String contains the character '%c'\n", char)
		}
	}
}

3. Using strings.Index

Another way to check if a substring or character is present in a string is by using the Index or IndexRune function from the strings package. These functions return the start index of the first instance of the substring/character in the string, or -1 if the substring/character is not present.

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Hello, Gophers!"
	substr := "Goph"

	if strings.Index(str, substr) != -1 {
		fmt.Printf("String contains '%s'\n", substr)
	} else {
		fmt.Printf("String does not contain '%s'\n", substr)
	}
}

Conclusion

These methods should help you determine whether specific characters or substrings are present in a given string in Go. Depending on the use-case, you can choose the most suitable function for your needs.

  1. Golang Check if Character is in String:

    • Use a loop to iterate over each character in the string and check for the desired character.
    • Example:
      package main
      
      import "fmt"
      
      func charInString(str string, char rune) bool {
          for _, c := range str {
              if c == char {
                  return true
              }
          }
          return false
      }
      
      func main() {
          text := "Hello, Golang!"
          charToCheck := 'o'
          result := charInString(text, charToCheck)
          fmt.Println(result)  // Output: true
      }
      
  2. String Contains Character Golang:

    • Use a loop or the strings package to check if a character is present in the string.
    • Example:
      package main
      
      import (
          "fmt"
          "strings"
      )
      
      func main() {
          text := "Golang"
          charToCheck := 'o'
      
          // Using strings.Contains
          result := strings.ContainsRune(text, charToCheck)
          fmt.Println(result)  // Output: true
      }
      
  3. Golang Check if Substring Exists in String:

    • Use the strings.Contains function to check if a substring is present in a string.
    • Example:
      package main
      
      import "fmt"
      
      func main() {
          text := "Hello, Golang!"
          substring := "Golang"
      
          result := strings.Contains(text, substring)
          fmt.Println(result)  // Output: true
      }
      
  4. How to Find if a Character is in a Golang String:

    • Use the loop approach to iterate over each character in the string and check for the desired character.
    • Example:
      // Refer to the example in point 1.
      
  5. Check if All Characters in a List are in a Golang String:

    • Iterate over the list of characters and check each one against the string.
    • Example:
      package main
      
      import "fmt"
      
      func allCharsInString(str string, chars []rune) bool {
          for _, char := range chars {
              if !charInString(str, char) {
                  return false
              }
          }
          return true
      }
      
      func main() {
          text := "Hello, Golang!"
          charsToCheck := []rune{'H', 'o', 'l'}
          result := allCharsInString(text, charsToCheck)
          fmt.Println(result)  // Output: true
      }
      
  6. Golang String Contains Any of Multiple Characters:

    • Iterate over the list of characters and check if any of them is present in the string.
    • Example:
      package main
      
      import "fmt"
      
      func anyCharInString(str string, chars []rune) bool {
          for _, char := range chars {
              if charInString(str, char) {
                  return true
              }
          }
          return false
      }
      
      func main() {
          text := "Hello, Golang!"
          charsToCheck := []rune{'x', 'y', 'o'}
          result := anyCharInString(text, charsToCheck)
          fmt.Println(result)  // Output: true
      }
      
  7. Using strings.Contains in Golang:

    • The strings.Contains function checks if one string contains another string.
    • Example:
      package main
      
      import "fmt"
      
      func main() {
          text := "Hello, Golang!"
          substring := "Golang"
      
          result := strings.Contains(text, substring)
          fmt.Println(result)  // Output: true
      }
      
  8. Golang Check if String Contains Only Specific Characters:

    • Iterate over each character in the string and check if it is in the allowed characters set.
    • Example:
      package main
      
      import "fmt"
      
      func onlyAllowedChars(str string, allowedChars []rune) bool {
          for _, char := range str {
              if !charInString(string(allowedChars), char) {
                  return false
              }
          }
          return true
      }
      
      func main() {
          text := "Go123"
          allowedChars := []rune{'G', 'o', '1', '2', '3'}
          result := onlyAllowedChars(text, allowedChars)
          fmt.Println(result)  // Output: true
      }
      
  9. Efficient Ways to Check Character Presence in Golang String:

    • For large strings, consider using a map to store character presence for faster lookups.
    • Example:
      package main
      
      import "fmt"
      
      func efficientCharInString(str string, char rune) bool {
          charSet := make(map[rune]bool)
          for _, c := range str {
              charSet[c] = true
          }
          return charSet[char]
      }
      
      func main() {
          text := "Hello, Golang!"
          charToCheck := 'o'
          result := efficientCharInString(text, charToCheck)
          fmt.Println(result)  // Output: true
      }
      
  10. Golang Rune and String Comparison for Character Presence:

    • Compare individual runes instead of converting to strings for character presence checks.
    • Example:
      package main
      
      import "fmt"
      
      func runeInString(str string, char rune) bool {
          for _, c := range str {
              if c == char {
                  return true
              }
          }
          return false
      }
      
      func main() {
          text := "Hello, Golang!"
          charToCheck := 'o'
          result := runeInString(text, charToCheck)
          fmt.Println(result)  // Output: true
      }