如何在如此简单的字符串中分别获取整数和字符?

发布于 2024-12-08 04:26:21 字数 212 浏览 1 评论 0原文

我有这样的字符串: "7d" 、 "5m" 、 "95d" 等。

我需要找到简单的方法来分别获取整数和字符。

我怎样才能做到这一点:

int number = GetNumber("95d"); //should return 95
char code = GetCode("95d"); // should return d

I have strings like: "7d" , "5m" , "95d" etc.

I need to find simple way to be able to get integer and char in the end separately.

How can I achieve this:

int number = GetNumber("95d"); //should return 95
char code = GetCode("95d"); // should return d

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

甜味超标? 2024-12-15 04:26:21

这些是表达式:

[^\d]+ <- not digit
\d+ <- digits


EDIT

    static int GetNumber(string text)
    {
        string pat = @"\d+";
        int output;
        // Instantiate the regular expression object.
        Regex r = new Regex(pat, RegexOptions.IgnoreCase);
        Match m = r.Match(text);
        if (int.TryParse(m.Value, out output))
            return output;
        else
            return int.MinValue; // something unlikely
    }

    static char GetChar(string text)
    {
        string pat = @"[^\d]";
        int output;
        // Instantiate the regular expression object.
        Regex r = new Regex(pat, RegexOptions.IgnoreCase);
        Match m = r.Match(text);
        return m.Value.Length == 1 ? m.Value[0] : '\0';
    }

您实际上只需要创建该 RegExp 对象一次,而不是在每次方法调用时创建。

These are the expressions:

[^\d]+ <- not digit
\d+ <- digits


EDIT

    static int GetNumber(string text)
    {
        string pat = @"\d+";
        int output;
        // Instantiate the regular expression object.
        Regex r = new Regex(pat, RegexOptions.IgnoreCase);
        Match m = r.Match(text);
        if (int.TryParse(m.Value, out output))
            return output;
        else
            return int.MinValue; // something unlikely
    }

    static char GetChar(string text)
    {
        string pat = @"[^\d]";
        int output;
        // Instantiate the regular expression object.
        Regex r = new Regex(pat, RegexOptions.IgnoreCase);
        Match m = r.Match(text);
        return m.Value.Length == 1 ? m.Value[0] : '\0';
    }

You really only need to create that RegExp object once, not on each method call.

泼猴你往哪里跑 2024-12-15 04:26:21

RegEx 解决方案的简单替代方案。

string letters = Seperate( "95d",  c => Char.IsLetter( c ) );
string numbers = Seperate( "95d", c => Char.IsNumber( c ) );

static string Seperate( string input, Func<char,bool> p )
{
    return new String( input.ToCharArray().Where( p ).ToArray() );
}

您可以将“单独”作为字符串的扩展方法,以使事情变得更清晰。

Simple alternative to the RegEx solutions.

string letters = Seperate( "95d",  c => Char.IsLetter( c ) );
string numbers = Seperate( "95d", c => Char.IsNumber( c ) );

static string Seperate( string input, Func<char,bool> p )
{
    return new String( input.ToCharArray().Where( p ).ToArray() );
}

You could make 'Seperate' an extension method on string to make things a bit cleaner.

心房敞 2024-12-15 04:26:21
string s = "95d";
int number = Int32.Parse(s.Substring(0, s.Length - 1));
char code = Char.Parse(s.Substring(s.Length - 1));
string s = "95d";
int number = Int32.Parse(s.Substring(0, s.Length - 1));
char code = Char.Parse(s.Substring(s.Length - 1));
简单 2024-12-15 04:26:21
public int GetNumber(string input)
{
    string result = "";

    foreach (Char c in input)
    {
        if (Char.IsDigit(c))
            result += c;
    }

    return Convert.ToInt32(result);
}

public string GetCode(string input)
{
    string result = "";

    foreach (Char c in input)
    {
        if (!Char.IsDigit(c))
            result += c;     // or return the char if you want only the first one.
    }

    return result;
}

没有测试,但对我来说,这看起来是实现这一目标的最佳方法。与其他答案相比,它也是提供最大灵活性的方法。

public int GetNumber(string input)
{
    string result = "";

    foreach (Char c in input)
    {
        if (Char.IsDigit(c))
            result += c;
    }

    return Convert.ToInt32(result);
}

public string GetCode(string input)
{
    string result = "";

    foreach (Char c in input)
    {
        if (!Char.IsDigit(c))
            result += c;     // or return the char if you want only the first one.
    }

    return result;
}

Did not test but to me it looks like the best way to achieve this. It also is the method that provides the most flexibility compared to other answers.

浅暮の光 2024-12-15 04:26:21

正则表达式可能有点过分了——你已经证明的例子有一个非常简单、一致的格式。尝试以下函数作为起点:

public int GetNumber(string input)
{
   return int.Parse(input.Substring(0, input.Length - 1));
}


public char GetCode(string input)
{
   return input.Last();
}

我说“作为起点”是因为您需要考虑边缘情况 - 您将如何处理空字符串?字符串是否可以以多个字母字符结尾,如果是,您将如何处理?希望这些例子能让车轮转动起来。

A regex is probably overkill -- the examples you've proved have a very simple, consistent format. Try the following functions as a starting point:

public int GetNumber(string input)
{
   return int.Parse(input.Substring(0, input.Length - 1));
}


public char GetCode(string input)
{
   return input.Last();
}

I say "as a starting point" because you'll need to consider edge cases -- how will you handle empty strings? Can a string end with more than one letter character, and if so, how will you handle this? Hopefully these examples get the wheels turning.

泅渡 2024-12-15 04:26:21
    private char GetChar(string t)
    {
        return t.Substring(t.Length - 1, 1)[0];
    }

    private int GetNumber(string t)
    {
        return Int32.Parse(t.Substring(0, t.Length - 1));
    }

编辑: GetNumber 函数的第二个版本使用“TryParse”而不是“Parse”:

    private int GetNumber(string t)
    {
        int result;
        if(Int32.TryParse(t.Substring(0, t.Length - 1), out result) == false)
        {
             // you can handle here incorrect 't' value if you want
        }
        return result;
    }
    private char GetChar(string t)
    {
        return t.Substring(t.Length - 1, 1)[0];
    }

    private int GetNumber(string t)
    {
        return Int32.Parse(t.Substring(0, t.Length - 1));
    }

Edit: second version of GetNumber function with 'TryParse' instead of 'Parse':

    private int GetNumber(string t)
    {
        int result;
        if(Int32.TryParse(t.Substring(0, t.Length - 1), out result) == false)
        {
             // you can handle here incorrect 't' value if you want
        }
        return result;
    }
り繁华旳梦境 2024-12-15 04:26:21

给你:

public class NumberSuffixParser
{
    private static readonly Regex rxPattern = new Regex( @"^(?<number>\d+(\.\d+)?)(?<suffix>\p{L}+)$" , RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture ) ;

    public void Parse( string value , out decimal number , out string suffix )
    {
        if ( value == null ) throw new ArgumentNullException("value") ;
        Match match = rxPattern.Match( value ) ;
        if ( ! match.Success ) throw new ArgumentOutOfRangeException("value") ;
        number = decimal.Parse( match.Groups["number"].Value ) ;
        suffix =                match.Groups["suffix"].Value   ;
        return ;
    }

    public decimal ParseNumber( string value )
    {
        decimal number ;
        string  suffix ;
        Parse( value , out number , out suffix ) ;
        return number ;
    }

    public string ParseSuffix( string value )
    {
        decimal number ;
        string  suffix ;
        Parse( value , out number , out suffix ) ;
        return suffix ;
    }

}

另一种稍微简单但相当灵活的方法如下。它会很乐意解析“789xyz”、“1234”或“abcde”等内容。如果没有找到整数前缀,则返回 0。后缀是整数前缀后面的任何内容:如果没有找到后缀,则返回 nil ('')。

public static void Parse( string value , out int number , out string suffix )
{
  number = 0 ;
  int i = 0 ;
  for ( i = 0 ; i < value.Length && char.IsDigit( value[i] ) ; ++i )
  {
     number *= 10 ;
     number += ( value[i] - '0' ) ;
  }
  suffix = value.Substring(i) ;
  return ;
}

Here you go:

public class NumberSuffixParser
{
    private static readonly Regex rxPattern = new Regex( @"^(?<number>\d+(\.\d+)?)(?<suffix>\p{L}+)$" , RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture ) ;

    public void Parse( string value , out decimal number , out string suffix )
    {
        if ( value == null ) throw new ArgumentNullException("value") ;
        Match match = rxPattern.Match( value ) ;
        if ( ! match.Success ) throw new ArgumentOutOfRangeException("value") ;
        number = decimal.Parse( match.Groups["number"].Value ) ;
        suffix =                match.Groups["suffix"].Value   ;
        return ;
    }

    public decimal ParseNumber( string value )
    {
        decimal number ;
        string  suffix ;
        Parse( value , out number , out suffix ) ;
        return number ;
    }

    public string ParseSuffix( string value )
    {
        decimal number ;
        string  suffix ;
        Parse( value , out number , out suffix ) ;
        return suffix ;
    }

}

Another, slightly more simplistic, but quite flexible approach follows. It will happily parse stuff like '789xyz', '1234' or 'abcde'. If it doesn't find a integer prefix, it returns 0. The suffix is whatever follows the integer prefix: if it doesn't find a suffix, it returns nil ('').

public static void Parse( string value , out int number , out string suffix )
{
  number = 0 ;
  int i = 0 ;
  for ( i = 0 ; i < value.Length && char.IsDigit( value[i] ) ; ++i )
  {
     number *= 10 ;
     number += ( value[i] - '0' ) ;
  }
  suffix = value.Substring(i) ;
  return ;
}
请你别敷衍 2024-12-15 04:26:21

你可以尝试这样的事情:

static string getNumber(String str)
{
    StringBuilder sb = new StringBuilder();
    foreach (char chr in str)
    {
        try
        {
            int x = int.Parse(chr.ToString());
            sb.Append(chr);
        } catch (Exception ex) {
            return sb.ToString();
        }
    }

    return null;
}

static string getCode(String str)
{
    StringBuilder sb = new StringBuilder();
    foreach (char chr in str)
    {
        try
        {
            int x = int.Parse(chr.ToString());
        }
        catch (Exception ex)
        {
            sb.Append(chr);
        }
    }

    return sb.ToString();
}



// 95
Console.WriteLine(getNumber("95d"));
// a
Console.WriteLine(getCode("95d"));

You can try something like this:

static string getNumber(String str)
{
    StringBuilder sb = new StringBuilder();
    foreach (char chr in str)
    {
        try
        {
            int x = int.Parse(chr.ToString());
            sb.Append(chr);
        } catch (Exception ex) {
            return sb.ToString();
        }
    }

    return null;
}

static string getCode(String str)
{
    StringBuilder sb = new StringBuilder();
    foreach (char chr in str)
    {
        try
        {
            int x = int.Parse(chr.ToString());
        }
        catch (Exception ex)
        {
            sb.Append(chr);
        }
    }

    return sb.ToString();
}



// 95
Console.WriteLine(getNumber("95d"));
// a
Console.WriteLine(getCode("95d"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文