-3

I have specific questions for my project

input = "3d6"

I want to convert this string some parts to integer. For instance I want to use input[0] like integer. How can I do this?

3
  • 2
    i, err := strconv.Atoi(input[:1]) Commented Jun 27, 2018 at 23:49
  • Go doesn't have type casting. You're also not talking about typecasting at all. You're talking about type conversion and string parsing. Commented Jun 28, 2018 at 10:43
  • More important: What have you tried, and what problems did you encounter? Show your code. Commented Jun 28, 2018 at 10:43

1 Answer 1

1

There's two problems here:

How to convert a string to an integer

The most straightforward method is the Atoi (ASCII to integer) function in the strconv package., which will take a string of numeric characters and coerce them into an integer for you.

How to extract meaningful components of a known string pattern

In order to use strconv.Atoi, we need the numeric characters of the input by themselves. There's lots of ways to slice and dice a string.

  • You can just grab the first and last characters directly - input[:1] and input[2:] are the ticket.

  • You could split the string into two strings on the character "d". Look at the split method, a member of the strings package.

  • For more complex problems in this space, regular expressions are used. They're a way to define a pattern the computer can look for. For example, the regular expression ^x(\d+)$ will match on any string that starts with the character x and is followed by one or more numeric characters. It will provide direct access to the numeric characters it found by themselves.

    • Go has first class support for regular expressions via its regexp package.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.