PlayDave
PlayDave

Reputation: 21

Strings Split and Join

I'm a go novice, I have data as follows Time Server Type Class Method-Message. with the help of json field delimiter "|" manage to have the following data Time|Server|Type|Class|Method-Message I want to split by - in the forth index which is |Method-Message then append a field delimiter "|" then join to end up with the following Time|Server|Type|Class|Method|Message.have tried to split the data with n = s[6 : 6+strings.Index(s[6:], "/")] what it did was to remove -Message then ended up with Time|Server|Type|Class|Method then i append a field delimiter then ended up with Time|Server|Type|Class|Method|Message| but couldn't append the-Message it was removed from the data.

Upvotes: 0

Views: 6505

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109404

I'm not sure why you are using strings.Index(s[6:], "/") when there is no / character in your original string, but you can replace the and - characters in a few ways:

With your original attempt of split and join twice:

msg := "Time Server Type Class Method-Message"
msg = strings.Join(strings.Split(msg, " "), "|")
msg = strings.Join(strings.Split(msg, "-"), "|")

Or slightly more efficiently, by only joining once:

msg := "Time Server Type Class Method-Message"
parts := strings.Split(msg, " ")
parts = append(parts[:4], strings.Split(parts[4], "-")...)
newMsg := strings.Join(parts, "|")

Or with multiple calls to strings.Replace:

newMsg := strings.Replace(strings.Replace(msg, " ", "|", -1), "-", "|", -1)

Or with a single regular expression:

newMsg := regexp.MustCompile(`[ -]`).ReplaceAllString(msg, "|")

Upvotes: 8

Related Questions