Method 1: Using Regular Expressions
using System; using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string text = "123abc";
string numberString = Regex.Match(text, @"\d+").Value; // Extracts continuous digits
int number = int.Parse(numberString); // Converts the string to an integer
Console.WriteLine(number);
}
}
Method 2: Manual Iteration
using System;
public class Program
{
public static void Main()
{
string text = "123abc";
string numberString = "";
foreach (char c in text)
{
if (char.IsDigit(c))
{
numberString += c;
}
}
int number = int.Parse(numberString); // Converts the collected digits into an integer
Console.WriteLine(number);
}
}
Regular Expressions: This method uses the Regex class to identify and extract digits from the string efficiently. It's ideal for handling complex patterns quickly but might be less intuitive if you're not familiar with regex syntax.
Manual Iteration: This method involves checking each character to see if it's a digit and then forming the integer manually. It offers more control and is straightforward, making it easier to understand if you're new to regular expressions.
Both methods will correctly convert the string "123abc" to the integer 123. Choose based on your preference for simplicity or flexibility.
12ab3c? Would you want12or3or123?