猿问

如何在字符串数组golang上实现删除范围?

如何RemoveRange在 golang 中实现方法?它是 C# 中的一种方法,如下所示


我想RemoveRange在我的字符串数组上实现方法,hashCode并在删除这些范围的情况下返回新的修改数组。


func removeRange(hashCode []string, idx int, count int) []string {

    var temp []string

    for i, s := range hashCode {

            fmt.Println(i, s)

      // confuse here on what to do

    }


    return temp

}


呼唤远方
浏览 248回答 3
3回答

精慕HU

只需将切片切片 until idx,跳过count元素并将其余元素附加到第一次切片的结果中:func removeRange(hashCode []string, idx int, count int) []string {    return append(hashCode[:idx], hashCode[idx+count:]...)}测试它:s := []string{"0", "1", "2", "3", "4", "5"}fmt.Println(s)s = removeRange(s, 1, 2)fmt.Println(s)哪些输出(在Go Playground上尝试):[0 1 2 3 4 5][0 3 4 5]注意:上述实现不检查索引是否有效(是否在范围内)。如果没有,代码可能会恐慌。如果需要,请添加必要的检查。注意#2:上述实现修改了传入切片的元素,返回的切片将共享参数的后备数组。如果你想避免这种情况,如果你想保持输入不变并为结果分配一个新切片,那么这样做:func removeRange(hashCode []string, idx int, count int) []string {    result := make([]string, 0, len(hashCode)-count)    result = append(result, hashCode[:idx]...)    result = append(result, hashCode[idx+count:]...)    return result}在Go Playground上试试这个。

qq_遁去的一_1

在 golang 中,您根本不需要为此提供方法或函数。Go 切片可以在适当位置进行子切片和附加,这就是您可以快速轻松地从任何切片中删除子集的方法。假设您要删除 2 个元素,从索引 2 开始,您只需编写:Sub := append(original [:2], original [4:]...)演示这是如何工作的:original[:2]创建从 0 开始的子切片,长度为 2 个元素(因此索引 0 和 1)append因为对于第一部分,我们要添加切片的其余部分,减去我们要跳过/删除的范围original[4:]创建另一个子切片,这次从索引 4 开始,并在任何original结束处结束。就像我们没有在第一个子切片中明确提到 0 作为起点一样,通过在此处不指定元素的数量,golang 将仅包含切片中的所有剩余元素。...因为append是一个可变参数函数(内置,但你明白了),我们需要传入我们想要附加的每个元素作为新参数。...运算符扩展子切片并将每个元素作为单独的参数传入。因为我们将新切片分配给了新变量,original将保持不变,所以如果要覆盖切片,只需将其分配给相同的变量即可。注意我是在手机上写的,所以标记和代码可能不太正确,但这至少应该回答你的问题

梵蒂冈之花

我已经使用//注释解释了代码,如果没有注释,代码是不言自明的。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os")func RemoveRange(s []string, index, count int) []string {&nbsp; &nbsp; sLen := len(s)&nbsp; &nbsp; // Similar semantics to match (similar) the behavior of&nbsp; &nbsp; // C# implementation&nbsp; &nbsp; switch {&nbsp; &nbsp; case index < 0, count < 0: // arguments are not valid&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintln(os.Stderr, "error: argument out of range error")&nbsp; &nbsp; &nbsp; &nbsp; return s&nbsp; &nbsp; case index+count-1 >= sLen: // range results in exceeding the limit&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintln(os.Stderr, "error: argument error")&nbsp; &nbsp; &nbsp; &nbsp; return s&nbsp; &nbsp; }&nbsp; &nbsp; // Create a slice p and pre-allocate the size required&nbsp; &nbsp; // to store the resultant slice after removing range.&nbsp; &nbsp; // Result := s[:] -> s[:index] + s[index+count:]&nbsp; &nbsp; // Remove := s[index:index+count-1]&nbsp; &nbsp; p := make([]string, 0, sLen-count)&nbsp; &nbsp; p = append(p, s[:index]...)&nbsp; &nbsp; p = append(p, s[index+count:]...)&nbsp; &nbsp; return p}func main() {&nbsp; &nbsp; s := []string{"0", "1", "2", "3", "4", "5"}&nbsp; &nbsp; fmt.Println(s)&nbsp; &nbsp; r := RemoveRange(s, 1, 3)&nbsp; &nbsp; fmt.Println(r)}输出:[0 1 2 3 4 5][0 4 5]
随时随地看视频慕课网APP

相关分类

Go
我要回答