string to int


See On Github

Data

Contributor

Generic placeholder thumbnail

by jcla1

in go

Tags

conversion

Source Code

package stringToInt

import "math"

func StringToInt(str string) int {
	exp := len(str) - 1
	total := 0

	for i := 0; i < len(str); i++ {
		if str[i] >= '0' && str[i] <= '9' {
			total += int(str[i]-48) * int(math.Pow10(exp))
			exp -= 1
		}
	}

	return total
}
package stringToInt

import "testing"

func TestStringToInt(t *testing.T) {
	str := []string{"0", "1", "2", "100", "123", "123455426"}
	ints := []int{0, 1, 2, 100, 123, 123455426}

	var result int

	for i, v := range str {
		result = StringToInt(v)
		if result != ints[i] {
			t.Errorf("StringToInt(%s) = %d, wanted %d", v, result, ints[i])
		}
	}
}