获取子字符串的索引

35

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


2
你可能只需使用指针就能实现你想要的功能,而无需担心长度。 - pmg
@国家 - 没有理由你不能投票(可能只有投票频率有限制)。 - KevinDTimm
7个回答

69

使用指针减法。

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

1
糟糕,char *str = "abracabcabcabcabc" :-) - pmg
啊,他的“source”字符串以abc开头,然后继续... :-) - Robert S. Barnes
1
谢谢大家!由于某些原因,我无法投票,所以只能说谢谢了。 - Country

6

newptr - source会给你偏移量。


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

pos = dest - source;

抱歉,我并不清楚这段文本的含义,请提供更多上下文信息。 - pmg
@pmg - 没关系 - "以'abc'开头" 仍然会创建正确的结果,因为strstr()一旦成功就停止查找。 - KevinDTimm
我会使用malloc分配一个数组,以使示例更完整。当然,我也会进行一些错误检查;-) - Robert S. Barnes
@RobertS.Barnes - 你本来可以的,但你没有做到 ;) - KevinDTimm
谢谢大家!由于某些原因我无法投票,所以我只能说谢谢。 - Country

3

这是一个带有偏移特性的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;
}

2

如果你有子字符串第一个字符的指针,并且该子字符串在源字符串的末尾,则:

  • strlen(substring) 将给出它的长度。
  • substring - source 将给出起始索引。

谢谢大家!由于某些原因我无法投票,所以我只能说谢谢。 - Country

2
其他人说得没错——substring - source确实是起始索引。但你不需要它:你会将它用作对source进行索引的位置。所以编译器会计算source + (substring - source)作为新地址,但几乎所有情况下只使用substring就足够了。 这里有一个优化和简化的提示。

1
谢谢大家!由于某些原因我无法投票,所以只能说谢谢。 - Country

0
一个函数,通过起始和结束单词从字符串中剪切出一个单词。
    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
    }

5
问题涉及C语言,不是C++。 - Robert S. Barnes
在C++中有更简单的方法 - 使用string::Find方法和字符串构造函数string(const string& str, size_t pos, size_t n = npos); - Alecs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接