我有 char * source ,我希望从中获取提取,我知道它是从符号“abc”开始,并在源结束时结束。使用 strstr ,我可以得到更好的,但不是位置,没有位置,我不知道子串的长度。如何在纯C中获取子字符串的索引?
答案 0 :(得分:40)
使用指针减法。
char *str = "sdfadabcGGGGGGGGG";
char *result = strstr(str, "abc");
int position = result - str;
int substringLength = strlen(str) - position;
答案 1 :(得分:6)
newptr - source
会给你抵消。
答案 2 :(得分:3)
char *source = "XXXXabcYYYY";
char *dest = strstr(source, "abc");
int pos;
pos = dest - source;
答案 3 :(得分:2)
如果你有指向子串的第一个字符的指针,并且子字符串在源字符串的末尾结束,那么:
strlen(substring)
会给你它的长度。substring - source
会为您提供开始索引。答案 4 :(得分:2)
这是带有偏移功能的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;
}
答案 5 :(得分:1)
正式其他人是正确的 - substring - source
确实是起始指数。但你不需要它:你会用它作为source
的索引。因此,编译器会将source + (substring - source)
计算为新地址 - 但对于几乎所有用例,只需substring
即可。
只是提示优化和简化。
答案 6 :(得分:1)
通过开始和结束单词从字符串中删除单词的功能
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
}