In java, getting the length of a string is very simple:
String str = "wk";
int len = str.length();
System.out.println("字符串str的长度为:" + len);
Then in C/C++, it is realized by pointer movement :
int getLength(char *string); // 函数声明
int main() {
char *str = "wk";
int len = getLength(str);
LOGI("字符串str的长度为:%d", len)
return 0;
}
/**
* @return 字符串的长度
*/
int getLength(char *string) {
int count = 0;
while (*string) { // string != NULL 则一直循环
string++; // 指针移动
count++;
}
return count;
}
In the getLength function, a string is received, and the string itself is also a pointer of char type . Because the pointer is at the beginning by default, the length of the string can be calculated by moving the pointer forward with ++ (self-incrementing)
In C language, pointers (no matter how many levels of pointers) can be moved back and forth by ++ (self-increment) or -- (self-decrement)