Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent to the Python len() function?

Tags:

c++

I have an integer and need to find out how many digits are in it.

like image 813
rectangletangle Avatar asked Sep 29 '10 03:09

rectangletangle


2 Answers

For positive numbers, use log10:

int a = 1234;
int len = static_cast<int>(log10(a)+1.);

If you need to be thorough:

int length(int a)
{
  int b = abs(a);
  if (b == 0) return 1;
  return static_cast<int>(log10(b)+1.);
}

With that said, it would be a better choice to do repeated division by 10 in practice.

int length(int a)
{
  int b = 0;
  for (a = abs(a); a != 0; b++, a /= 10) continue;
  return b;
}
like image 160
JoshD Avatar answered Sep 16 '22 19:09

JoshD


You probably mean you have a string containing numbers rather than an int in python:

>>> i = 123456789
>>> len(i)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> len(str(i))
9

If this is also the case in c++ it's easy to find the length of a string using:

my_str_value.length()

or for a C string using strlen

like image 32
Peter McG Avatar answered Sep 16 '22 19:09

Peter McG