2011-09-21 170 views
16

我有char * source,我想从中提取subsrting,我知道从符号“abc”开始,并在源结束处结束。与strstr我可以得到poiner,但不是位置,没有位置,我不知道子字符串的长度。我怎样才能得到纯C的子字符串的索引?获取子字符串的索引

+1

你可以用指针来做你想要的,而不用担心长度。 – pmg

+0

@Country - 没有理由不投票(这可能会限制频率) – KevinDTimm

回答

33

使用指针减法。

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

oops'char * str =“abracabcabcabcabc”':-) – pmg

+0

ahh,他的“源”字符串以abc开头,然后继续... :-) –

+0

谢谢大家!我不能投票的原因,所以我只能说,谢谢 – Country

6

newptr - source会给你抵消。

+0

谢谢大家!我不能因为某种原因投票,所以我只能说谢谢 – Country

+0

我认为你需要25个代表投票。 – mkb

2

如果你有指向字符串的第一个字符,和子在源字符串的结尾结束,则:

  • strlen(substring)会给你它的长度。
  • substring - source会给你开始索引。
+0

谢谢大家!我不能投票,因此我只能说谢谢 – Country

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

pos = dest - source; 
+0

oops'source =“abracadabcabcabcabc”':) – pmg

+0

@pmg - 无所谓 - “以'abc'开头”仍然创建正确的结果作为strstr ()停止查找,一旦它成功 – KevinDTimm

+0

我想用malloc分配一个数组只是为了使示例更完整。当然,我也会做一些错误检查;-) –

1

形式上,其它的是正确的 - substring - source确实开始索引。但是你不需要它:你可以使用它作为source的索引。因此,编译器计算source + (substring - source)作为新地址 - 但只有substring对于几乎所有用例都足够了。

只是提示优化和简化。

+1

谢谢大家!我不能投票的原因,所以我只能说,谢谢你 – Country

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 
    } 
+4

问题是关于C,而不是C++ –

+0

在C + +有更简单的方法来做到这一点 - 使用字符串::查找方法和字符串构造函数字符串(常量字符串&str ,size_t pos,size_t n = npos); – Alecs

0

这里切一个字一个字符串的函数是有偏移的特征对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; 
}