2011-09-21 169 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; 
}