欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-14 08:30:10
/// /// 获取字符串最长的数字 /// ///
/// <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;
}

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