Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the "string length" of an int

Tags:

c

basically I want to return the number of digits in the int -> values like this:

(int)1 => 1
(int)123 => 3
(int)12345678 => 8

I know nothing about C, so please bear with me. I know objective c, but I use ints and floats instead of NSNumbers. I realise I could convert the ints into objective c objects, but this seems faffy, and if I can do it with C I'll know it for the future.

Thanks

like image 682
Thomas Clayson Avatar asked Nov 10 '10 09:11

Thomas Clayson


People also ask

How do you calculate the length of a string?

As you know, the best way to find the length of a string is by using the strlen() function.

Can you check the length of an int?

The length of an integer means the total number of digits present in that integer. We can find the length of integer by using the following approaches: Using while loop. Using String.

Can I use strlen for int?

strlen wouldn't work too well for integers, simply because of the way integers are stored. Assuming 32bit ints, they take four bytes (16 bit integers will use 2 bytes) and for Windows PC's they stored in little endian format - the least significant byte of the integer value will occupy the lowest address.

How do you find the length of a string in C?

String Length in C Using Built-In Library Function The length of a string can be found using the built-in library function strlen() in string. h header file. It returns the length of the string passed to it (ignoring the null character). The string is passed to the strlen() function, which returns its length.


2 Answers

use

int d = (value == 0 ? 1 : (int)(log10(value)+1));

Note that this doesnt work for negative numbers, you'll have to use

int d = (value == 0 ? 1 : ((int)(log10(fabs(value))+1) + (value < 0 ? 1 : 0)));

which adds 1 for the minus sign, if value is negative.

like image 174
MartinStettner Avatar answered Nov 18 '22 07:11

MartinStettner


Probably much faster than using log or int-to-string conversion and without using any library functions is this:

int nDigits(int i)
{
  if (i < 0) i = -i;
  if (i <         10) return 1;
  if (i <        100) return 2;
  if (i <       1000) return 3;
  if (i <      10000) return 4;
  if (i <     100000) return 5;
  if (i <    1000000) return 6;      
  if (i <   10000000) return 7;
  if (i <  100000000) return 8;
  if (i < 1000000000) return 9;
  return 10;
}

EDIT after Jeff Yates concerns:

For those who worry about int sizes different from 32-bits (similar to pmg's solution but still faster because multiplication is faster than division :-)

#include <limits.h>

#define PO10_LIMIT (INT_MAX/10)


int nDigits(int i)
{
  int n,po10;

  if (i < 0) i = -i;
  n=1;
  po10=10;
  while(i>=po10)
  {
    n++;
    if (po10 > PO10_LIMIT) break;
    po10*=10;
  }
  return n;
}
like image 45
Curd Avatar answered Nov 18 '22 05:11

Curd