C,如何查找字符串中所有字符实例的索引位置

时间:2014-01-01 15:34:03

标签: c arrays string

我在C中有一个字符串。我想获取字符串中该字符的所有实例的索引位置。

它出现不止一次,所以我需要返回所有字符的索引。

示例是包含str1的字符串Banana。角色' a'在索引位置找到:1,3,5

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:2)

为什么不这样呢?

for (i = 0; i < strlen(str); i++)
  if (str[i] == ch)
      location[index++] = i;

答案 1 :(得分:0)

strstr()会有所帮助。

有关详情,请参阅以下内容。

http://www.cplusplus.com/reference/cstring/strstr/