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

说明

  • 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切片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值