C algorithm function: Gets the number of the maximum length in a string

  • 2021-10-15 11:20:56
  • OfStack


/// <summary>
///  Gets the longest number in a string 
/// </summary>
/// <param name="inputStr"> Input string </param>
/// <returns> Maximum number </returns>
public string GetMaxLenNumber(string inputStr)
{
  // Put the characters in a string into an array for easy processing 
  char[] strCharArray = inputStr.ToCharArray();
  // Where to start processing 
  int startPos = 0;
  // Character length currently processed 
  int tempCharCount = 0;
  // Maximum length of numbers 
  int maxLen = 0;
  // Total length of array 
  int len = strCharArray.Length;
  int pos = 0;
  while (startPos < len)
  {
    // Temporary maximum length in loop 
    int tempMax = 0;
    while (tempCharCount + startPos < len)
    {
      // Character to start processing 
      char c = strCharArray[tempCharCount + startPos];
      if (char.IsNumber(c))
      {
        // If it's a number 
        tempMax++;
        if (tempMax > maxLen)
        {
          maxLen = tempMax;
          pos = startPos;
        }            
      }
      else
      {
        // Not numbers 
        tempMax = 0;
        startPos++;
        break;
      }
      tempCharCount++;
    }
    if (startPos + tempCharCount == len)
    {
      break;
    }
    tempCharCount = 0;       
  }
  string s = inputStr.Substring(pos, maxLen);
  return s;
}

Related articles: