亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何避免字符串中出現特殊字符

如何避免字符串中出現特殊字符

Go
德瑪西亞99 2023-07-10 10:48:00
我正在解析包含 URL 的 XML,并且我想迭代此 XML 以獲取所有 URL 并向每個 URL 發出請求,但字符串包含換行符\n。如何避免 URL 中出現新行?Go版本是go1.12.7 darwin/amd64。我有解決這個問題的方法,我只是從字符串中刪除這個字符。package mainimport (    "encoding/xml"    "fmt"    "io/ioutil"    "log"    "net/http"    "strings")type SitemapIndex struct {    Locations []string `xml:"sitemap>loc"`}type NewsMap struct {    Keyword  string    Location string}type News struct {    Titles    []string `xml:"url>news>title"`    Keywords  []string `xml:"url>news>keywords"`    Locations []string `xml:"url>loc"`}func main() {    var s SitemapIndex    var n News    newsMap := make(map[string]NewsMap)    resp, _ := http.Get("https://washingtonpost.com/news-sitemaps/index.xml")    bytes, _ := ioutil.ReadAll(resp.Body)    xml.Unmarshal(bytes, &s)    for _, Location := range s.Locations {        tempURL := strings.Replace(Location, "n", "", -1) // how to avoid new lines character in url?        resp, err := http.Get(tempURL)                // do some stuff...}如果位置上沒有此替換方法,我會收到錯誤 parsehttps://www.washingtonpost.com/news-sitemaps/politics.xml: net/url: invalid control character in URLexit status 1以下是示例 XML 文件https://www.washingtonpost.com/news-sitemaps/politics.xml
查看完整描述

1 回答

?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

XML 文本包含 Dave C 在評論中提到的換行符。由于 URL 中不允許出現換行符,因此您必須刪除換行符。

通過用“”替換換行符(而不是n)來修復。注意反斜杠。

tempURL := strings.Replace(Location, "\n", "", -1)

更好的解決方法是使用 strings.TrimSpace (Dave C 也提到過)。這將處理文件中可能存在的所有無關空白:

tempURL := strings.TrimSpace(Location)


查看完整回答
反對 回復 2023-07-10
  • 1 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號