Table of Contents
Question content
Workaround
Home Backend Development Golang Replace repeated substrings in a string by replacing only one of them

Replace repeated substrings in a string by replacing only one of them

Feb 09, 2024 am 08:15 AM

Replace repeated substrings in a string by replacing only one of them

php Xiaobian Yuezi replaces repeated substrings in a string and only replaces one of them. It is a common problem. In string processing, sometimes we need to replace repeated substrings in a string, but we do not want to replace all repeated substrings, but only one of them. This can retain other identical substrings while achieving the replacement effect we want. In PHP, we can achieve this requirement with the help of some built-in functions and regular expressions. Below, we will introduce in detail how to implement the method of replacing only one of the repeated substrings in the string.

Question content

I am making a simple executioner game using go, but I encountered an error, the unknown_string string (will be shown in the code) has _ characters, so guess the letters The other players can see the length of the word, and whenever a player enters the correct letter, I want it to replace the nth (n depends on the index where the letter is found in the word) _ character with that letter, this has been successful, but there are one question. If a word has two repeated letters, only one of them is replaced.

I created a separate function called iterate (this function was created because I wanted to avoid nested code) to iterate over all indices. But it doesn't work, the code is as follows:

package main

import (
    "fmt"
    "strings"
)

var input string
var word string
var unknown_word []string
var unknown_word_string string
var index int
var guesses int
var change_unknown_word_string []byte

func main() {
    fmt.Println("Welcome to hangman")
    fmt.Println("Player 1, choose a word!")
    fmt.Scan(&word)
    for i := 1; i <= len(word); i++ {
        unknown_word = append(unknown_word, "_")
    }
    unknown_word_string = strings.Join(unknown_word, "")
    for {
        fmt.Println("Player 2, guess a letter or a word")
        fmt.Println(unknown_word_string)
        fmt.Scan(&input)
        if guesses == 6 {
            fmt.Println("Player 2 lost! Player 1's word was: ", word)
            break
        } else if unknown_word_string == input {
            fmt.Println("Player 1 lost! Player 2 guessed the word by guessing the letter!")
        }
        if strings.Contains(word, input) && word != input {
            index = strings.Index(word, input)
            iterate()
            fmt.Println("You guessed a letter!")
        } else if word == input {
            fmt.Println("Player 1 lost! Player 2 guessed the word by guessing the whole word!")
            break
        } else {
            fmt.Println("Nothing found")
            guesses++
        }
    }
}
func iterate() {
    change_unknown_word_string = []byte(unknown_word_string)
    for i := 0; i < len(change_unknown_word_string); i++ {
        if change_unknown_word_string[i] == change_unknown_word_string[index] {
            change_unknown_word_string[i] = []byte(input)[0]
        }
    }
    unknown_word_string = string(change_unknown_word_string)
}
Copy after login

Workaround

Comparisonif change_unknown_word_string[i] == change_unknown_word_string[index] doesn't make any sense since unknown_word_string is obviously included in these positions _.

You should compare word[i] == input[0] in the loop.

But please note that converting string to a byte array does not support unicode. It's better to use runes (unicode code points) so you're no longer limited to latin1 characters.

func iterate() {
    needle := []rune(input)[0]
    haystack := []rune(word)
    buf := []rune(unknown_word_string)
    for i := range haystack {
        if haystack[i] == needle {
            buf[i] = needle
        }
    }
    unknown_word_string = string(buf)
}
Copy after login

Note: This comparison is wrong

if unknown_word_string == input {
            fmt.Println("Player 1 lost! Player 2 guessed the word by guessing the letter!")
        }
Copy after login

It should be ifunknown_word_string == word and come after the call to iterate().

The above is the detailed content of Replace repeated substrings in a string by replacing only one of them. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

See all articles