Extract only numbers or characters from a set of characters (string)


Introduction

Hello, I hope that all of you guys doing well. Anyway let’s focus what i am trying to say? As a programmer frequently i need to do extract only numbers from an alphanumeric set of characters (string). Even sometimes need to do exactly the opposite for example extract only characters (string) from set of an alphanumeric characters (string). So i would like to share a very very simple but very efficient and strong way to do this..

Using the code

A sample code is given below:

 private String foo 
       (
             String p_inputValue
       )
       {
           string rectVal = string.Empty;

           for (int i = 0; i < p_inputValue.Length; i++)
           {
               // validating the current character is a number or not
               if (!(Char.IsDigit(p_inputValue[i])))
                   rectVal += p_inputValue[i];
           }

           return rectVal;
        
       } // end function foo

Input: A123B333C45D66E6F7GH

output: ABCDEFGH

 

if you want to do exactly the opposite you just need to change the “if” condition just like below:

 if (Char.IsDigit(p_inputValue[i]))

Input: A123B333C45D66E6F7GH

output:123333456667

History

  • 28th August, 2017: Initial post

2 thoughts on “Extract only numbers or characters from a set of characters (string)

Add yours

Leave a comment

Create a free website or blog at WordPress.com.

Up ↑