Sum of non contiguous numbers in a given alpha-numeric string

Given a string of alpha-numeric characters, return the sum of numbers that are non contiguous. For example if the given string is "abc45ef13g1", the function should return 59 i.e. 45+13+1.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine(ReturnSum("abc45ef13g1"));

        }

        public static int ReturnSum(string str)

        {

            int sum = 0;

            string num = "";

            for (int i = 0; i < str.Length; i++)

            {

                if (char.IsDigit(str[i]))

                {

                    num = num + str[i];

                }

                else

                {

                    if (num.Length != 0)

                    {

                        sum = sum + int.Parse(num);

                        num = "";

                    }

                }

            }

            if (num.Length != 0)

            {

                sum = sum + int.Parse(num);

                return (sum);

            }

            return (sum);

        }

    }

}

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s