Golang中实现strpos函数的方法

Golang中实现strpos函数的方法 你好,我有一个PHP代码想转换成Go语言:

$file = '/usr/etcetc';
$filesize = filesize($file);
$filech1 = file_get_contents('/etc/oct');
$posttt = strpos($filech1, '/etc/ggl/soft');
$posttt1 = strpos($filech1, 'myttt');
if ($posttt !== FALSE && 1 < $filesize && !$posttt1) {
}

我们可以通过 strings.Index 来实现 strpos 的功能,但是 $posttt !== FALSE!$posttt1 在Go语言中该如何处理呢?当我尝试这样做时,出现了错误:

关于 !$posttt1 的错误: invalid operation: operator ! not defined for filech2 (variable of type int)

关于 $posttt !== FALSE 的错误: cannot convert false (untyped bool constant) to intcompiler


更多关于Golang中实现strpos函数的方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

你好,我找到了解决方案。 我们可以使用 posttt != -1

更多关于Golang中实现strpos函数的方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,strings.Index 函数返回的是匹配子串的起始索引(int类型),如果没有找到则返回-1。这与PHP的strpos返回FALSE不同,需要调整条件判断逻辑。

以下是转换后的Go代码示例:

package main

import (
    "io/ioutil"
    "os"
    "strings"
)

func main() {
    file := "/usr/etcetc"
    
    // 获取文件大小
    fileInfo, err := os.Stat(file)
    if err != nil {
        // 处理错误
        return
    }
    filesize := fileInfo.Size()
    
    // 读取文件内容
    filech1, err := ioutil.ReadFile("/etc/oct")
    if err != nil {
        // 处理错误
        return
    }
    content := string(filech1)
    
    // 使用strings.Index实现strpos功能
    posttt := strings.Index(content, "/etc/ggl/soft")
    posttt1 := strings.Index(content, "myttt")
    
    // 转换条件判断
    // $posttt !== FALSE 转换为 posttt != -1
    // !$posttt1 转换为 posttt1 == -1
    // 1 < $filesize 转换为 filesize > 1
    if posttt != -1 && filesize > 1 && posttt1 == -1 {
        // 条件成立时的逻辑
    }
}

关键转换点:

  1. $posttt !== FALSEposttt != -1
  2. !$posttt1posttt1 == -1
  3. PHP的filesize()返回字节数,Go的fileInfo.Size()返回int64
  4. 文件读取使用ioutil.ReadFile(),需要转换为字符串进行字符串操作

错误原因解释:

  • !$posttt1 错误:Go中!运算符只能用于bool类型,不能用于int类型
  • $posttt !== FALSE 错误:Go是强类型语言,不能直接将bool与int比较

如果需要在多个位置进行类似判断,可以封装辅助函数:

func strpos(haystack, needle string) int {
    return strings.Index(haystack, needle)
}

func strposFound(pos int) bool {
    return pos != -1
}

// 使用示例
if strposFound(posttt) && filesize > 1 && !strposFound(posttt1) {
    // 条件逻辑
}
回到顶部