Parsing

Parsing is the process of reading a string and converting it into another type . It is a specific kind of explicit type conversion.

It comes up often when a program receives input from the user. In most languages, user input always arrives as text — even if the user typed a number. Parsing lets you turn that text into a usable value.

For example, if the user types 1, the program receives the string "1". To use it as a number, you need to parse it:

string input = Console.ReadLine();
int number = int.Parse(input);

int.Parse() reads the string and returns the integer it represents. If the string cannot be interpreted as a number — for example if it’s "abc" — the program will crash.

input_value = input()
number = int(input_value)

int() reads the string and returns the integer it represents. If the string cannot be interpreted as a number — for example if it’s "abc" — the program will crash.

let inputValue = prompt();
let number = parseInt(inputValue);

parseInt() reads the string and returns the integer it represents. If the string cannot be interpreted as a number — for example if it’s "abc" — it returns NaN (Not a Number) instead of crashing.

Parsing can fail if the string doesn’t match the expected type. Always make sure the input is valid before parsing, or handle the failure gracefully.

Resources#