Click here to Skip to main content
15,893,161 members
Articles / Programming Languages / C# 7.0
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
2.09/5 (5 votes)
27 Aug 2017CPOL 6.1K   2
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:

C#
 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:

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

Input: A123B333C45D66E6F7GH

output:123333456667

History

  • 28th August, 2017: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionI will not rate it but.. Pin
Tammam Koujan28-Aug-17 1:52
professionalTammam Koujan28-Aug-17 1:52 
GeneralThis is bad code Pin
larsgregersen27-Aug-17 23:29
larsgregersen27-Aug-17 23:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.