我做了一个小函数,它填充一个分配的内存块,其中包含给定字符串中给定字符的每个位置,并返回一个指向内存块的指针。
这个函数唯一的问题是没有办法检查内存块的大小;所以我还做了一个函数来计算字符串中给定字符的出现次数。
这是一个使用示例:
/*count occurences of char within a given string*/
size_t strchroc(const char *str, const char ch)
{
int c = 0;
while(*str) if(*(str++) == ch) c++;
return c;
}
/*build array of positions of given char occurences within a given string*/
int *chrpos(const char *str, const char ch)
{
int *array, *tmp, c = 0, i = 0;
if(!(array = malloc(strlen(str) * sizeof(int)))) return 0x00;
while(str[c])
{
if(str[c] == ch) array[i++] = c;
c++;
}
if(!(tmp = realloc(array, i * sizeof(int)))) return 0x00;
array = tmp;
return array;
}
int main(void)
{
char *str = "foobar foobar"; //'o' occurs at str[1], str[2], str[8], and str[9]
int *array, b = 0, d;
if(!(array = chrpos(str, 'o'))) exit(1); //array[0] = 1, array[1] = 2, array[2] = 8, array[3] = 9
/*
* This is okay since I know that 'o'
* only occures 4 times in str. There
* may however be cases where I do not
* know how many times a given char
* occurs so I figure that out before
* utilizing the contents of array.
* I do this with my function strchroc.
* Below is a sample of how I would
* utilize the data contained within
* array. This simply prints out str
* and on a new line prints the given
* char's location within the str
* array
*/
puts(str);
while(b < (int) strchroc(str, 'o')) //loop once for each 'o'
{
for(d = 0; d < (b == 0 ? array[b] : array[b] - array[b - 1] - 1); d++) putc((int) ' ', stdout);
printf("%d", array[b]);
b++;
}
}
输出:
foobar foobar
12 89
我唯一担心的是,如果这两个功能之一失败,则无法正确使用数据。我正在考虑char
将字符串中出现的次数作为参数,chrpos
但即便如此我仍然必须调用这两个函数。
我想知道是否有人对如何做到这一点有任何建议,这样我只需要一个函数来构建数组。
我能想到的唯一方法是将 char 出现的次数array[0]
存储array[1] through array[char_occurences]
到char
.
如果有人有更好的主意,我将不胜感激。