I would like to ask such a question, how can you calculate the length of a string without using the function for calculating the length of the string strlen () ?
Answer 1, authority 100%
You can. The length of the string is essentially the position number of the ‘\ 0’ character:
size_t my_strlen (const char * s) {
const char * cur = s;
for (; * cur; ++ cur);
return cur - s;
}
Answer 2, authority 31%
It is possible by iterating over the pointer (from the beginning of the line to the terminating character \ 0
) and counting the number of these same iterations – the same as strlen ()
. But why is it?
Answer 3, authority 23%
int size_s (char * s)
{
int i;
for (i = 0; s [i]! = '\ 0'; i ++);
return i;
}
I used to write something like this.
Answer 4
This is faster on 32-bit processors:
size_t strlen (const char * s)
{
const char * p = s;
for (;;)
{
uint32 c = * ((uint32 *) p);
if ((c - 0x01010101u) & amp; 0x80808080u)
{
if ((c & amp; 0x000000ffu) == 0) return p-s + 0;
if ((c & amp; 0x0000ff00u) == 0) return p-s + 1;
if ((c & amp; 0x00ff0000u) == 0) return p-s + 2;
if ((c & amp; 0xff000000u) == 0) return p-s + 3;
}
p + = 4;
}
}
This assumes that the input string is aligned to a 32-bit border (of course, it will work without alignment, but then the whole point is lost).
Answer 5
File main.c
# include & lt; stdio.h & gt;
int main (int argc, char * argv []) {
int i = 1;
for (; i & lt; argc; i ++) {
char * pStr = argv [i];
int length = 0;
while (* pStr ++! = '\ 0') {
length ++;
}
printf ("% d \ n", length);
}
}
Collecting
gcc main.c
Launch
./ a.out some_string
The length of all strings passed as parameters (some_string) will be counted
Iteration starts from one, because the first parameter is always the name of the program.
This is how strlen works =)
Answer 6
This is not a tricky way:
size_t strlen (const char * s) {
const char * p;
for (p = s; * p; ++ p);
return p - s;
}
Answer 7
Well, how could you forget it? Although platform-specific, of course 🙂
xor eax, eax
mov ecx, -1
mov edi, some_string
mov ebx, edi
cld
push ds
pop es
repne scasb
mov eax, edi
sub eax, ebx
dec eax
Answer 8
Method without loops and pointers, free of charge (originally made for numeric arrays, but also suitable for strings, you just need to subtract the terminating zero)
# define SIZE_OF_ARRAY (_array) (sizeof (_array) / sizeof (_array [0]) - 1)
Answer 9
# include & lt; iostream & gt;
#include & lt; string & gt;
using namespace std;
int number (string chislosimvolov, int i);
int main ()
{
string chisla;
int i;
cout & lt; & lt; "\ nEnter stroky:";
cin & gt; & gt; chisla;
cout & lt; & lt; "Number of symbols in it is:" & lt; & lt; number (chisla, int (chisla.size ()));
}
int number (string chislosimvolov, int i)
{
int t;
if (i == -1) t = 0;
else
t = number (chislo, i-1)
;
return t;
}