gpt4 book ai didi

戈朗 : Skipping Whitespace in a file

转载 作者:数据小太阳 更新时间:2023-10-29 03:06:45 26 4
gpt4 key购买 nike

在用 Go 读取文件时,我试图跳过所有的空格;但是,我在寻找正确的方法时遇到问题。任何帮助将不胜感激

file, err := os.Open(filename) // For read access.
this.file = file
if err != nil {
log.Fatal(err)
}
//skip white space

c := make([]byte, 1)

char, err := this.file.Read(c)

//skip white space
for {
//catch unintended errors
if err != nil && err != io.EOF {
panic(err)
}
if err == io.EOF || !unicode.IsSpace(int(c)) {
break
}
//get next
char, err := this.file.Read(c)
}

我只是简单地尝试为文件创建一个扫描器,以一次读取一个字符并忽略空格

编辑

我改变了一些东西来使用 bufio.Reader;但是我仍然遇到问题逐字符读取文件的正确方法是什么,以便它可以与特定符号(如“A”)进行比较,但也可以忽略空格,即 unicode.isSpace(rune)

char, size, err := this.reader.ReadRune()
//skip white space and comments
for {
//catch unintended errors
if err != nil && err != io.EOF {
panic(err)
}
if err == io.EOF {
break
}

//skip it when their is no data or a space
if size != 0 && char == '{' {
//Ignore Comments
//Documentation specifies no nested comments
for char != '}' {
char, size, err = this.reader.ReadRune()
}
} else if !unicode.IsSpace(char) {
break
}

// Do something with the byte
fmt.Print(char)

//get next
char, size, err = this.reader.ReadRune()
}

最佳答案

除非我误解了您的问题,否则您似乎希望在遇到空格时使用 continue 语句。

c := make([]byte, 100)

n, err := this.file.Read(c)

//skip white space
for {
//catch unintended errors
if err != nil && err != io.EOF {
panic(err)
}
if err == io.EOF {
break
}

for i := 0; i < n; i++ {
ch := c[i]

switch ch {
case '{': // Do something
case '}': // Do something else
default:
if unicode.IsSpace(int(ch)) {
continue
}
// Do whatever
}
}

//get next
n, err = this.file.Read(c)
}

我不知道你为什么一次读取一个字节,但我还是那样保留它以防它是故意的。至少,我认为您希望读取完整的 Unicode 字符而不是单个字节。

关于戈朗 : Skipping Whitespace in a file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32769420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com