【发布时间】:2021-06-15 05:48:10
【问题描述】:
需要一个函数来检查我是否存在子字符串并给我创建此函数的位置,我想知道 C 标头中是否已经存在类似的东西以及它是如何工作的。
这个自己的函数给出了子字符串Hello world的开始位置!如果我搜索世界给 6 如果找不到字符串,则给 -1
#include <stdio.h>
#include <string.h>
int findfstr(const char mainstring[], const char substring[]){
// int = findstring(mainstring,substring) give position if found and -1 if not
int main_length = strlen(mainstring); // Read the mainstring length
int subs_length = strlen(substring); // Read the substring length
int where = 0; // Set to 0 the var of start position
int steps = (main_length - subs_length); //Retrive the numbers of the chars without substring
int cicle = 0; // Set to 0 the var used for increment steps
char found_string[subs_length]; // Set the Array to the substring length
if ( subs_length <= main_length){ // If substring is bigger tha mainstring make error
while (where == 0){ //loop until var "where are equal to 0"
//Stop loop if and when cicle is bigger than steps
if (cicle >= steps && where == 0){ where = -1;}
//retrive the substring and store in found_string
strncpy(found_string, mainstring+cicle, subs_length);
found_string[subs_length] = '\0'; //Add terminator char to end string
//If retrived string are equal to substring then set where with clicle value
if ((strcmp(found_string, substring) == 0 )) {
where = cicle;
}
cicle++; //add +1 to cicle
}
}else{ printf("\n substring is to big \n"); } //error message
return where;
}
int main(){
int fs = 0;
// This is how use the function
fs = findfstr("Hello world!","world");
if ( fs > 0 ){ printf("\n String found and start in: %d", fs);}
if ( fs < 0 ){ printf("\n String not found value: %d", fs);}
return 0;
}
输出:
String found and start in: 6
【问题讨论】:
-
@EugeneSh。我尝试了 strstr 但只检索子字符串而不是位置
-
它返回一个指针。从原始指针和返回的指针,您可以推断出位置。
-
@EugeneSh。我怎样才能担任这个职位? strstr() return char* 我需要 INT 索引
-
strstr() 返回的是指针而不是索引,但是你可以通过减去指向字符串开头的指针得到索引。
标签: c search substring c-strings function-definition