溫馨提示×

C語言求字符串長度的方法有哪些

小億
91
2024-05-21 09:59:28
欄目: 編程語言

  1. 使用strlen函數:可以通過調用標準庫函數strlen來獲取字符串的長度。例如:
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, World!";
    int len = strlen(str);
    printf("Length of the string: %d\n", len);
    return 0;
}
  1. 遍歷字符串:可以通過遍歷字符串的每個字符,直到遇到字符串結束符’\0’來計算字符串的長度。例如:
#include <stdio.h>

int main() {
    char str[] = "Hello, World!";
    int len = 0;
    while (str[len] != '\0') {
        len++;
    }
    printf("Length of the string: %d\n", len);
    return 0;
}
  1. 自己實現一個計算字符串長度的函數:可以自己實現一個函數來計算字符串的長度。例如:
#include <stdio.h>

int strLength(char *str) {
    int len = 0;
    while (*str != '\0') {
        len++;
        str++;
    }
    return len;
}

int main() {
    char str[] = "Hello, World!";
    int len = strLength(str);
    printf("Length of the string: %d\n", len);
    return 0;
}

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女