---
title: "String to Interger"  
description: "String to Interger"  
author: "Steilla Mitchel"  
published: 2024-06-11  
updated: 2024-06-12  
canonical: https://www.mindstick.com/forum/160719/string-to-interger  
category: "c#"  
tags: ["c#", ".net"]  
reading_time: 2 minutes  

---

# String to Interger

Implement the `myAtoi(string s)` [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server), which converts a [string](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) to a 32-bit signed [integer](https://answers.mindstick.com/qa/113667/write-code-for-roman-to-integer).

The [algorithm](https://www.mindstick.com/blog/119/implementing-cryptography-in-c-sharp-dot-net-by-using-sha1-algorithm) for `myAtoi(string s)` is as follows:

1. **Whitespace**: Ignore any [leading](https://answers.mindstick.com/qa/100394/5-iitians-who-made-india-proud-by-leading-the-world-s-biggest-companies) whitespace (`" "`).
2. **Signedness**: Determine the sign by [checking if](https://www.mindstick.com/forum/34435/checking-if-file-exists-in-asp-dot-net-mvc-4) the next [character](https://www.mindstick.com/articles/23551/an-investigate-distinctive-seafood-restaurant-for-your-image-stamp-character) is `'-'` or `'+'`, assuming positivity is neither present.
3. **[Conversion](https://www.mindstick.com/forum/1734/conversion-from-32-bit-integer-to-4-chars)**: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the [result](https://www.mindstick.com/blog/12011/advantages-of-getting-result-oriented-seo-from-an-agency) is 0.
4. **Rounding**: If the integer is out of the 32-bit signed integer [range](https://www.mindstick.com/articles/23243/complete-troubleshooting-tips-for-belkin-n300-range-extender-setup) `[-231, 231 - 1]`, then round the integer to remain in the range. Specifically, integers less than `-231` should be rounded to `-231`, and integers greater than `231 - 1` should be rounded to `231 - 1`.

Return the integer as the final result.

## Replies

### Reply by Ravi Vishwakarma

Let's write code for **String to Integer** in C#. Create **MyAtoi** function to convert **string to integer**.

```cs
        /// <summary>
        /// This function return an integer after converting a string
        /// </summary>
        /// <param name="s"></param>
        /// <returns>return an integer, after converting to a string.</returns>
        public static int MyAtoi(string s)
        {
            //check string is is null or empty
            if (string.IsNullOrEmpty(s))
            {
                return 0;
            }

            int i = 0, sign = 1, result = 0, n = s.Length;

            // Discard leading whitespaces
            while (i < n && s[i] == ' ')
            {
                i++;
            }

            // Check for optional sign
            if (i < n && (s[i] == '+' || s[i] == '-'))
            {
                sign = (s[i] == '-') ? -1 : 1;
                i++;
            }

            // Convert characters to digits and handle overflow/underflow
            while (i < n && s[i] >= '0' && s[i] <= '9')
            {
                int digit = s[i] - '0';

                // Check for overflow and underflow
                if (result > (int.MaxValue - digit) / 10)
                {
                    return (sign == 1) ? int.MaxValue : int.MinValue;
                }

                result = result * 10 + digit;
                i++;
            }

            return result * sign;
        }
```

Now call this function through `main()`.

```cs
using System;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main()
        {
            string[] array = { "42", " -042", "13-37c0d3", "0-1", "words and 987" };
            foreach (var item in array)
            {
                Console.WriteLine(Program.MyAtoi(item));
            }
        }

    }
}
```


---

Original Source: https://www.mindstick.com/forum/160719/string-to-interger

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
