取消多行字符串的缩进。

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

Unindent a multiline string value

问题

我不喜欢 Go 语言的多行字符串约定:

function main() {
  for {
    if something {
      text := `   Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna 
aliqua. 
   Ut enim ad minim veniam, quis nostrud exercitation 
ullamco laboris nisi ut aliquip ex ea commodo consequat.
      `
    }
  }
}

我更喜欢:

function main() {
  for {
    if something {
      text := `
           Lorem ipsum dolor sit amet, consectetur adipiscing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna
        aliqua. 
           Ut enim ad minim veniam, quis nostrud exercitation 
        ullamco laboris nisi ut aliquip ex ea commodo consequat.
      `
      // text = unindent(text, 8) ?
    }
  }
}

效率不是问题。

如何从字符串值的每行开头删除固定数量的空格?

英文:

I don't like the Go convention for multiline strings:

function main() {
  for {
    if something {
      text := `   Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna 
aliqua. 
   Ut enim ad minim veniam, quis nostrud exercitation 
ullamco laboris nisi ut aliquip ex ea commodo consequat.
      `
    }
  }
}

I prefer:

function main() {
  for {
    if something {
      text := `
           Lorem ipsum dolor sit amet, consectetur adipiscing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna
        aliqua. 
           Ut enim ad minim veniam, quis nostrud exercitation 
        ullamco laboris nisi ut aliquip ex ea commodo consequat.
      `
      // text = unindent(text, 8) ?
    }
  }
}

Efficiency isn't a concern.

How do I remove a fixed number of spaces from the start of each line in my string value?

答案1

得分: 2

这是一个简单的strings.Replace()调用:

text = strings.Replace(text, "\n        ", "\n", -1)

替换前后的输出(在Go Playground上尝试):

Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. 
Ut enim ad minim veniam, quis nostrud exercitation 
ullamco laboris nisi ut aliquip ex ea commodo consequat.


Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. 
Ut enim ad minim veniam, quis nostrud exercitation 
ullamco laboris nisi ut aliquip ex ea commodo consequat.

请注意,这仍然会在文本的开头和结尾留下换行符。如果你还想摆脱它们,可以使用strings.Trim()

text = strings.Replace(text, "\n        ", "\n", -1)
text = strings.Trim(text, "\n")

注意:strings.TrimSpace()可能首先会想到,但它不是一个好选择,因为它还会删除第一行的缩进(" Lorem"),这是不需要的。我们只是想摆脱额外的前缀和后缀换行符。

验证差异:

text = strings.Replace(text, "\n        ", "\n", -1)
fmt.Printf("%q\n", text)
text = strings.Trim(text, "\n")
fmt.Printf("%q\n", text)

输出:

"\n   Lorem ipsum dolor sit amet, consectetur adipiscing elit,\nsed do eiusmod tempor incididunt ut labore et dolore magna\naliqua. \n   Ut enim ad minim veniam, quis nostrud exercitation \nullamco laboris nisi ut aliquip ex ea commodo consequat.\n"
"   Lorem ipsum dolor sit amet, consectetur adipiscing elit,\nsed do eiusmod tempor incididunt ut labore et dolore magna\naliqua. \n   Ut enim ad minim veniam, quis nostrud exercitation \nullamco laboris nisi ut aliquip ex ea commodo consequat."

将其封装为一个辅助函数:

func unindent(s string, spaces int) string {
    old := "\n" + strings.Repeat(" ", spaces)
    s = strings.Replace(s, old, "\n", -1)
    return strings.Trim(s, "\n")
}

并使用它:

text = unindent(text, 8)

创建old可替换字符串的另一种方法:

func unindent(s string, spaces int) string {
    old := fmt.Sprintf("%*c", -spaces-1, '\n')
    s = strings.Replace(s, old, "\n", -1)
    return strings.Trim(s, "\n")
}
英文:

That's a simple strings.Replace() call:

text = strings.Replace(text, "\n        ", "\n", -1)

Output before and after the replace (try it on the Go Playground):

           Lorem ipsum dolor sit amet, consectetur adipiscing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna
        aliqua. 
           Ut enim ad minim veniam, quis nostrud exercitation 
        ullamco laboris nisi ut aliquip ex ea commodo consequat.
        

   Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. 
   Ut enim ad minim veniam, quis nostrud exercitation 
ullamco laboris nisi ut aliquip ex ea commodo consequat.

Note that this will still leave newline character at the beginning and at the end of your text. If you also want to get rid of them, you may use strings.Trim():

text = strings.Replace(text, "\n        ", "\n", -1)
text = strings.Trim(text, "\n")

Note: strings.TrimSpace() would come first to mind, but it's not a good choice as that would also remove the indentation from the first line (" Lorem") which is unwanted. We really just want to get rid of extra prefix and postfix newlines.

To verify the difference:

text = strings.Replace(text, "\n        ", "\n", -1)
fmt.Printf("%q\n", text)
text = strings.Trim(text, "\n")
fmt.Printf("%q\n", text)

Output:

"   Lorem ipsum dolor sit amet, consectetur adipiscing elit,\nsed do eiusmod tempor incididunt ut labore et dolore magna\naliqua. \n   Ut enim ad minim veniam, quis nostrud exercitation \nullamco laboris nisi ut aliquip ex ea commodo consequat."```

**To wrap it in a helper function:**

    func unindent(s string, spaces int) string {
    	old := "\n" + strings.Repeat(" ", spaces)
    	s = strings.Replace(s, old, "\n", -1)
    	return strings.Trim(s, "\n")
    }

And using it:

    text = unindent(text, 8)

An alternative way to create the `old` replaceable string:

    func unindent(s string, spaces int) string {
        old := fmt.Sprintf("%*c", -spaces-1, '\n')
        s = strings.Replace(s, old, "\n", -1)
        return strings.Trim(s, "\n")
    }

  [1]: https://golang.org/pkg/strings/#Replace
  [2]: https://play.golang.org/p/9969WsvPbL
  [3]: https://golang.org/pkg/strings/#Trim
  [4]: https://golang.org/pkg/strings/#TrimSpace




</details>



# 答案2
**得分**: 1

你可以尝试这个不是很好但简单的方法。

```go
func main() {
    text := "Lorem ipsum dolor sit amet, consectetur adipiscing elit,\n" +
            "sed do eiusmod tempor incididunt ut labore et dolore magna\n" +
            "aliqua.\n" +
            "Ut enim ad minim veniam, quis nostrud exercitation\n" +
            "ullamco laboris nisi ut aliquip ex ea commodo consequat."
    fmt.Println(text)
}
英文:

You can try this not a good but easy method.

func main() {
    text := &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit,\n&quot; +
            &quot;sed do eiusmod tempor incididunt ut labore et dolore magna\n&quot; +
            &quot;aliqua.\n&quot; +
            &quot;Ut enim ad minim veniam, quis nostrud exercitation\n&quot; +
            &quot;ullamco laboris nisi ut aliquip ex ea commodo consequat.&quot;
    fmt.Println(text)


}

huangapple
  • 本文由 发表于 2017年2月22日 19:48:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/42390549.html
匿名

发表评论

匿名网友

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

确定