我有一个 char * source,我想从中提取一个子字符串,我知道它从符号“abc”开始,并在源字符串的结尾处结束。使用 strstr 我可以得到指针,但没有位置信息,我不知道子字符串的长度。如何在纯C中获取子字符串的索引位置?
使用指针减法。
char *str = "sdfadabcGGGGGGGGG";
char *result = strstr(str, "abc");
int position = result - str;
int substringLength = strlen(str) - position;
char *str = "abracabcabcabcabc"
:-) - pmgnewptr - source
会给你偏移量。
char *source = "XXXXabcYYYY";
char *dest = strstr(source, "abc");
int pos;
pos = dest - source;
这是一个带有偏移特性的strpos函数的C语言版本...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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;
}
如果你有子字符串第一个字符的指针,并且该子字符串在源字符串的末尾,则:
strlen(substring)
将给出它的长度。substring - source
将给出起始索引。substring - source
确实是起始索引。但你不需要它:你会将它用作对source
进行索引的位置。所以编译器会计算source + (substring - source)
作为新地址,但几乎所有情况下只使用substring
就足够了。
这里有一个优化和简化的提示。
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
}