CSharp examples for Language Basics:string
Input a series of numbers separated by commas, parse them into integers and output the sum.
using System;// ww w . j a v a 2 s. co m class Program { public static void Main(string[] args) { Console.WriteLine("Input a series of numbers separated by commas:"); string input = Console.ReadLine(); char[] dividers = {',', ' '}; string[] segments = input.Split(dividers); int sum = 0; foreach(string s in segments) { if (s.Length > 0) { if (IsAllDigits(s)) { int num = 0; if (Int32.TryParse(s, out num)) { Console.WriteLine("Next number = {0}", num); sum += num; } } } } Console.WriteLine("Sum = {0}", sum); } public static bool IsAllDigits(string raw) { string s = raw.Trim(); if (s.Length == 0) { return false; } for(int index = 0; index < s.Length; index++) { if (Char.IsDigit(s[index]) == false) { return false; } } return true; } }