微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#算法函数:获取一个字符串中的最大长度的数字

/// <summary>
/// 获取字符串最长的数字
/// </summary>
/// <param name="inputStr">输入字符串</param>
/// <returns>最长数字</returns>
public string GetMaxLenNumber(string inputStr)
{
  //将字符串中的字符存放到数组中,便于处理
  char[] strChararray = inputStr.tochararray();
  //开始处理的位置
  int startPos = 0;
  //当前处理的字符长度
  int tempCharCount = 0;
  //数字的最长长度
  int maxLen = 0;
  //数组的总长度
  int len = strChararray.Length;
  int pos = 0;
  while (startPos < len)
  {
    //循环中的临时最大长度
    int tempMax = 0;
    while (tempCharCount + startPos < len)
    {
      //开始处理的字符
      char c = strChararray[tempCharCount + startPos];
      if (char.IsNumber(c))
      {
        //如果是数字
        tempMax++;
        if (tempMax > maxLen)
        {
          maxLen = tempMax;
          pos = startPos;
        }            
      }
      else
      {
        //不是数字
        tempMax = 0;
        startPos++;
        break;
      }
      tempCharCount++;
    }
    if (startPos + tempCharCount == len)
    {
      break;
    }
    tempCharCount = 0;       
  }
  string s = inputStr.Substring(pos,maxLen);
  return s;
}

以上就是本文的全部内容,希望能给大家一个参考,也希望大家多多支持编程小技巧。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐