Himaan Singh
Himaan Singh

Reputation: 707

Extracting only the substring containing letters from a string containing digits strings and symbols

I have a string that is like the following:

 string str = hello_16_0_2016;

What I want is to extract hello from the string. As in my program the string part can occur anywhere as it is autogenerated, so I cannot fix the position of my string.

For example: I can take the first five string from above and store it in a new variable.

But as occurring of letters is random and I want to extract only letters from the string above, so can someone guide me to the correct procedure to do this?

Upvotes: 1

Views: 618

Answers (3)

ΩmegaMan
ΩmegaMan

Reputation: 31686

But as occurring of letters is random and I want to extract only letters from the string above, so can someone guide me to the correct procedure to do this?

The following will extract the first text, without numbers anywhere in the string:

Console.WriteLine( Regex.Match("hello_16_0_2016", @"[A-Za-z]+").Value ); // "hello"

Upvotes: 0

Jcl
Jcl

Reputation: 28272

I'd use something like this (uses Linq):

var str = "hello_16_0_2016";
var result = string.Concat(str.Where(char.IsLetter));

Check it out

Or, if performance is a concern (because you have to do this on a tight loop, or have to convert hundreds of thousands of strings), it'd probably be faster to do:

var result = new string(str.Where(char.IsLetter).ToArray());

Check it too

Upvotes: 1

qJake
qJake

Reputation: 17139

Could you just use a simple regular expression to pull out only alphabetic characters, assuming you only need a-z?

using System.Text.RegularExpressions;

var str = "hello_16_0_2016";
var onlyLetters = Regex.Replace(str, @"[^a-zA-Z]", "");

// onlyLetters = "hello"

Upvotes: 1

Related Questions