Hi! I wonder how you can replace the null character to be able to read the length of the whole string. Because C only reads to the null character I was told so I have to replace it with something else.
The reason why my for loop has 7 is temporarly, just to make sure it can read all elements. Since strlen(str) returns 3 because of the null character.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int i;
char str[] = {'h', 'e', 'j', '\0', 'a', 'b', 'c'};
int array_length = sizeof(str)/sizeof(str[0]);
int characters_length = 0;
for(i=0; i<array_length; i++) {
if(str[i] == '\0') {
str[i] = ' ';
}
printf("%c",str[i]); //The string character by character
}
/** alternative way to do it */
printf("\nLength of array: %d\n\n\n", sizeof(str)/sizeof(str[0]));
printf("%s",str); //The whole string
characters_length = strlen(str); //assign string length to a variable
printf("\nThe string length is: %d\n\n",characters_length); //print the length
return 0;
}
C only reads to the null character
Yes, you are right.
Big thanks to paxdiablo for describing this. As he said @ StackOverflow: "strlen usually works by counting the characters in a string until a \0 character is found. A canonical implementation would be:
Code:
int len =0;
while(str[i] != '\0'){
len++;
}
I hope I helped. If you have any other question. Let me know!