获取子字符串的索引

我有char * source ,我想要从它中提取subsrting,我知道它是从符号“abc”开始,并在源结束时结束。 使用strstr我可以得到poiner,但不是位置,没有位置我不知道子串的长度。 如何获得纯C中子字符串的索引?

使用指针减法。

char *str = "sdfadabcGGGGGGGGG"; char *result = strstr(str, "abc"); int position = result - str; int substringLength = strlen(str) - position; 

newptr - source会给你偏移量。

 char *source = "XXXXabcYYYY"; char *dest = strstr(source, "abc"); int pos; pos = dest - source; 

如果您有指向子字符串的第一个字符的指针,并且子字符串在源字符串的末尾结束,则:

  • strlen(substring)会给你它的长度。
  • substring - source将为您提供起始索引。

正式其他是正确的 – substring - source确实是起始索引。 但是你不需要它:你会用它作为source索引。 所以编译器计算source + (substring - source)作为新地址 – 但是几乎所有用例只需要substring就足够了。

只是提示优化和简化。

通过开始和结束单词从字符串中删除单词的function

  string search_string = "check_this_test"; // The string you want to get the substring string from_string = "check"; // The word/string you want to start string to_string = "test"; // The word/string you want to stop string result = search_string; // Sets the result to the search_string (if from and to word not in search_string) int from_match = search_string.IndexOf(from_string) + from_string.Length; // Get position of start word int to_match = search_string.IndexOf(to_string); // Get position of stop word if (from_match > -1 && to_match > -1) // Check if start and stop word in search_string { result = search_string.Substring(from_match, to_match - from_match); // Cuts the word between out of the serach_string } 

这是带有偏移function的strpos函数的C版本……

 #include  #include  #include  int strpos(char *haystack, char *needle, int offset); int main() { char *p = "Hello there all y'al, hope that you are all well"; int pos = strpos(p, "all", 0); printf("First all at : %d\n", pos); pos = strpos(p, "all", 10); printf("Second all at : %d\n", pos); } int strpos(char *hay, char *needle, int offset) { char haystack[strlen(hay)]; strncpy(haystack, hay+offset, strlen(hay)-offset); char *p = strstr(haystack, needle); if (p) return p - haystack+offset; return -1; }