如何将ASCII结尾的字符串转换为值?

问题描述 投票:0回答:2

我对 C# 很陌生,但是我有其他语言的经验,包括 C/C++、Java 等。我正在尝试将 C# 中具有附加 ASCII 的字符串转换为整数,例如。

string text = "123abc";

我想要做的是从上面提取123并将其放入一个整数而不产生异常。

c#
2个回答
0
投票

您可以过滤掉字符串中不是数字的每个字符,然后使用

int.Parse
来解析结果字符串,使用类似 LINQ 的方法。使用
int.Parse
而不是
int.TryParse
应该没问题,因为我们过滤了所有非数字的内容。如果过滤后的数字字符串超出整数范围,它仍然可能会失败。

string original = "123abc";
IEnumerable<char> filtered = original.Where(x => Char.IsDigit(x));
string filteredString = new string(filtered.ToArray());
int number = int.Parse(filteredString);

或者一行(并使用一些语法糖):

var number = int.Parse(original.Where(Char.IsDigit).ToArray());

0
投票

方法一:使用正则表达式

使用系统;使用 System.Text.RegularExpressions;

公开课节目{ 公共静态无效主要() { 字符串文本=“123abc”; 字符串 numberString = Regex.Match(text, @"\d+").Value; // 提取连续数字 int 数字 = int.Parse(numberString); // 将字符串转换为整数

    Console.WriteLine(number);
} }

方法二:手动迭代

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.

两种方法都会正确地将字符串“123abc”转换为整数 123。根据您对简单性或灵活性的偏好进行选择。

© www.soinside.com 2019 - 2024. All rights reserved.