Go语言基础(codewars---8kyu和7kyu)

发布于:2022-12-11 ⋅ 阅读:(366) ⋅ 点赞:(0)

说明

  • Go语言从0开始的codewars代码记录,8kyu7kyu是一些语法题
  • 主要记录一些语法题中遇到的一些Best Practice,以学习Go语言库函数的使用方法
  • 代码很基础,所以不加注释了

一、String相关题

1、Abbreviate a Two Word Name

Description:

Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.
The output should be two capital letters with a dot separating them.

It should look like this:
Sam Harris => S.H
patrick feeney => P.F

Best Practice:

package kata

import "strings"

func AbbrevName(name string) string{
  x := strings.Index(name, " ")
  return strings.ToUpper(string(name[0]) + "." + string(name[x + 1]))
}

Tips:strings.Index(name, " ") 表示name中第一个为" "的字符下标

2、Convert a String to a Number!

Description:

We need a function that can transform a string into a number. What ways of achieving this do you know?
Note: Don't worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number.

Examples
"1234" --> 1234
"605"  --> 605
"1405" --> 1405
"-7" --> -7

Best Practice:

package kata

import "strconv"

func StringToNumber(str string) int {
  res, _ := strconv.Atoi(str)
  return res
}

Tips:
strconv.Atoi 表示将“1234” 这种只包含int类型元素的字符串转换成int类型
strconv.Itoa 表示将int类型转换成string类型

3、Reverse words

DESCRIPTION:

Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.

Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double  spaces"      ==> "elbuod  secaps"

Best Practice:

package kata

func ReverseWords(str string) string {
  var rev string
  var word string
  
  for _, i := range str {
    if i == ' ' {
      rev = rev + word + " " 
      word = ""
    } else {
      word = string(i) + word 
    } 
  }
  
  return rev + word
  }

4、Shortest Word

DESCRIPTION:

Simple, given a string of words, return the length of the shortest word(s).

String will never be empty and you do not need to account for different data types.

Best Practice:

package kata

import "strings"

func FindShort(s string) int {
  length := len(s)
  for _, word := range strings.Split(s, " "){
    if(length > len(word)){
      length = len(word)
    }
  }
  return length
}

Tips:
strings.Split(s, " ")" " 为分割点将s 分割成slice切片

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到