如果 line.startsWith(“something”),则不要写这一行和下一行。

huangapple go评论58阅读模式
英文:

If line.startsWith("something") don't write this line nor the next line

问题

我试图读取并编辑一个文件。

假设我有一个文件,内容如下:

a
b
c
d

我有如下代码:

if inputLine.startsWith("b"){
    // 寻找要放入这里的代码
}

那么我该如何避免将 b 和 c 写入新文件中呢?

所以新文件的内容看起来会是这样的:

a
d

希望这样表达清楚。

我已经尝试使用 continue。然而,它不会写入 b,但仍会写入 c

我还在寻求相同操作的相反方式的帮助,基本上是这样说:

if inputLine.startsWith("b"){
    删除 a 和 b
}

这样我就会得到:

c
d

谢谢 如果 line.startsWith(“something”),则不要写这一行和下一行。

编辑:

当尝试使用 continue 时,我尝试在 while 循环中这样做:

if inputLine.startsWith("b"){
    while(inputLine != "d"){
        continue;
}
}
英文:

I'm trying to read a file and edit it.

Let's say I have a file that says:

a
b
c
d

and I have code saying

if inputLine.startsWith("b"){
    looking for code to go in here
}

how do I then go about not writing neither b and c into the new file.

so the new file would look like this:

a
d

I hope that makes senses.

I've tried using continue. However, it doesn't write b but it still writes c.

I am also looking for help with doing the same thing but the other way round, basically saying:

if inputLine.startsWith("b"){
    delete a && b
}

so I will be left with:

c
d

Thank you 如果 line.startsWith(“something”),则不要写这一行和下一行。

edit:

When trying continue I tried doing this is a while loop like so:

if inputLine.startsWith("b"){
    while(inputLine != "d"){
        continue;
}
}

答案1

得分: 1

boolean skipnextLine = false;

// 假设您有一个循环,遍历每一行
for (...) {
    if (skipnextLine) {
        skipnextLine = false;
        continue; // 忽略当前行
    }

    if (inputLine.startsWith("b")) {
        skipnextLine = true; // 跳过下一行
        continue; // 忽略当前行
    }

    // 在这里执行您想要处理的未被跳过的行的操作
}
英文:
boolean skipnextLine = false;

// Assuming you have some loop that loops through each line
for(...) {
    if(skipnextLine) {
        skipnextLine = false;
        continue; // Ignore current line
    }

    if(inputLine.startsWith("b")) {
        skipnextLine = true; // Skip next line
        continue; // Ignore current line
    }

    // Do here what you want to do with the lines that are not skipped
}

答案2

得分: 0

看看这是否有效...
我们正在做的是创建一个整数以确定要跳过多少行,代码大部分都是自我解释的。

int linesToSkip = 0;
if (inputLine.startsWith("b")) {
    linesToSkip = 2;
}
if (linesToSkip > 0) {
    linesToSkip--;
    continue;
}
// 在这里处理未被跳过的行
英文:

see if this works...
what were doing is were creating an integer to know how many lines to skip, the code is mostly self explainitory

int linesToSkip = 0;
if(inputLine.startsWith("b")){
     linesToSkip = 2;
}
if(linesToSkip > 0){
     linesToSkip--;
     continue;
}
//do what you want here with the lines not skipped

huangapple
  • 本文由 发表于 2020年9月21日 21:28:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63993300.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定