我是新手,对我来说一直在使用split。最近,我遇到了一个问题,我想拆分一些东西,然后将拆分的字符保留在第二个切片中,而不是删除它,或者像SplitAfter一样将其保留在第一个切片中。
例如以下代码:
strings.Split("email@email.com", "@")
返回:["email", "email.com"]
strings.SplitAfter("email@email.com", "@")
返回:["email@", "email.com"]
获得["email", "@email.com"]
的最佳方法是什么?
答案 0 :(得分:3)
使用strings.Index查找@
和slice以获得两个部分:
var part1, part2 string
if i := strings.Index(s, "@"); i >= 0 {
part1, part2 = s[:i], s[i:]
} else {
// handle case with no @
}
答案 1 :(得分:0)
这对您有用吗?
<div class="col-md-4">
<a href="images/SC/SC-1.jpg" data-lightbox="SCTM" data-title="Science Center and Technology Museum">
<a href="images/SC/SC-Concept.jpg" data-lightbox="SCTM" data-title="Analysis">
<a href="images/SC/SC-Groundfloor.jpg" data-lightbox="SCTM" data-title="Floor Plans">
<a href="images/SC/SC-Floorplans.jpg" data-lightbox="SCTM" data-title="Floor Plans">
<a href="images/SC/interior.jpg" data-lightbox="SCTM" data-title="Ground Floor Interior View">
<a href="images/SC/SC-Sections2.jpg" data-lightbox="SCTM" data-title="Section Plan">
<a href="images/SC/SC-Sections.jpg" data-lightbox="SCTM" data-title="Section Plans">
<a href="images/SC/Landscape.jpg" data-lightbox="SCTM" data-title="Landscape View">
<div class="imageContainer">
<img src="images/SC/SC_cover.jpg" class="img-fluid">
<div class="imageOverlay">
<div class="imageText">
<h4>Science Center and Technology Museum</h4>
<h5>Project Location:</h5>
<p>Golden Horn/Istanbul</p>
<h5>Project Type:</h5>
<p>Museum</p>
<h5>Project Date:</h5>
<p>2017</p>
<h5>Project Area:</h5>
<p>17.000 sqm</p>
</div>
</div>
</div>
</a>
</a>
</a>
</a>
</a>
</a>
</a>
</a>
</div>
<div class="col-md-4">
然后梳理并创建一个字符串
s := strings.Split("email@email.com", "@")
address, domain := s[0], "@"+s[1]
fmt.Println(address, domain)
// email @email.com
答案 2 :(得分:0)
您可以使用bufio.Scanner
:
package main
import (
"bufio"
"strings"
)
func email(data []byte, eof bool) (int, []byte, error) {
for i, b := range data {
if b == '@' {
if i > 0 {
return i, data[:i], nil
}
return len(data), data, nil
}
}
return 0, nil, nil
}
func main() {
s := bufio.NewScanner(strings.NewReader("email@email.com"))
s.Split(email)
for s.Scan() {
println(s.Text())
}
}