251. Parse binary digits
Extract integer value i from its binary string representation s (in radix 2) E.g. "1101" -> 13
解析二进制数字
package main import ( "fmt" "reflect" "strconv" ) func main() { s := "1101" fmt.Println("s is", reflect.TypeOf(s), s) i, err := strconv.ParseInt(s, 2, 0) if err != nil { panic(err) } fmt.Println("i is", reflect.TypeOf(i), i) }
s is string 1101 i is int64 13
fn main() { let s = "1101"; // binary digits let i = i32::from_str_radix(s, 2).expect("Not a binary number!"); println!("{}", i); }
252. Conditional assignment
Assign to variable x the value "a" if calling the function condition returns true, or the value "b" otherwise.
条件赋值
package main import ( "fmt" ) func main() { var x string if condition() { x = "a" } else { x = "b" } fmt.Println(x) } func condition() bool { return "Socrates" == "dog" }
x = if condition() { "a" } else { "b" };
258. Convert list of strings to list of integers
Convert the string values from list a into a list of integers b.
将字符串列表转换为整数列表
package main import ( "fmt" "strconv" ) func main() { a := []string{"11", "22", "33"} b := make([]int, len(a)) var err error for i, s := range a { b[i], err = strconv.Atoi(s) if err != nil { panic(err) } } fmt.Println(b) }
fn main() { let a: Vec<&str> = vec!["11", "-22", "33"]; let b: Vec<i64> = a.iter().map(|x| x.parse::<i64>().unwrap()).collect(); println!("{:?}", b); }
259. Split on several separators
Build list parts consisting of substrings of input string s, separated by any of the characters ',' (comma), '-' (dash), '_' (underscore).
在几个分隔符上拆分
package main import ( "fmt" "regexp" ) func main() { s := "2021-03-11,linux_amd64" re := regexp.MustCompile("[,\\-_]") parts := re.Split(s, -1) fmt.Printf("%q", parts) }
fn main() { let s = "2021-03-11,linux_amd64"; let parts: Vec<_> = s.split(&[',', '-', '_'][..]).collect(); println!("{:?}", parts); }
266. Repeating string
Assign to string s the value of string v, repeated n times and write it out.
E.g. v="abc", n=5 ⇒ s="abcabcabcabcabc"
重复字符串
package main import ( "fmt" "strings" ) func main() { v := "abc" n := 5 s := strings.Repeat(v, n) fmt.Println(s) }
fn main() { let v = "abc"; let n = 5; let s = v.repeat(n); println!("{}", s); }