You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言中查找字符串数组中目标字符串的索引?

在C语言中查找字符串在字符串数组中的索引

C语言没有像Python那样内置的字符串数组索引查找函数,你需要手动遍历数组并逐个比较字符串来实现这个功能,核心是使用标准库的strcmp()函数判断字符串是否相等。

以下是一个完整的实现示例:

#include <stdio.h>
#include <string.h>

// 查找目标字符串在数组中的索引,未找到返回-1
int find_string_index(const char *arr[], int arr_length, const char *target) {
    for (int i = 0; i < arr_length; i++) {
        // strcmp返回0表示两个字符串完全相等
        if (strcmp(arr[i], target) == 0) {
            return i;
        }
    }
    // 遍历完数组未找到匹配项
    return -1;
}

int main() {
    const char *colors[] = {"red", "green", "blue"};
    // 计算数组长度:总字节数除以单个元素的字节数
    int arr_len = sizeof(colors) / sizeof(colors[0]);
    const char *target = "green";
    
    int index = find_string_index(colors, arr_len, target);
    if (index != -1) {
        printf("%d\n", index);
    } else {
        printf("未找到目标字符串\n");
    }
    
    return 0;
}

运行这段代码会输出:

1

关键说明:

  • strcmp()是<string.h>中的标准函数,用于比较两个C风格字符串,返回值为0时代表字符串完全匹配。
  • C语言无法直接获取数组的长度,所以需要手动计算(sizeof(数组)/sizeof(数组元素))或者将长度作为参数传入函数。
  • 如果需要处理空指针、空字符串等边界情况,可以在函数中添加额外的判断逻辑,比如先检查target或arr[i]是否为NULL。

内容的提问来源于stack exchange,提问作者user15298418

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 12:45:37