반응형
부분 문자열 색인 가져오기
나는 char * 소스를 가지고 있고, 나는 그것의 서브스크립팅에서 추출하고 싶습니다. 내가 알고 있는 것은 기호 "abc"에서 시작하여 소스가 끝나는 곳에서.strr을 사용하면 포인어를 얻을 수 있지만 위치는 얻을 수 없으며 위치가 없으면 서브스트링의 길이를 알 수 없습니다.순수 C에서 부분 문자열의 인덱스를 얻으려면 어떻게 해야 합니까?
포인터 뺄셈을 사용합니다.
char *str = "sdfadabcGGGGGGGGG";
char *result = strstr(str, "abc");
int position = result - str;
int substringLength = strlen(str) - position;
newptr - 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
}
언급URL : https://stackoverflow.com/questions/7500892/get-index-of-substring
반응형
'sourcetip' 카테고리의 다른 글
요소의 한쪽에만 드롭 섀도우를 만드는 방법은? (0) | 2023.10.15 |
---|---|
두 개의 사용자 지정 게시물 유형 동일한 범주 (0) | 2023.10.15 |
스파크 상태의 데이터 프레임 열 업데이트 (0) | 2023.10.15 |
jQuery 1.8+를 포함하여 jQuery Contains 대소문자를 구분하지 않게 하려면 어떻게 해야 합니까? (0) | 2023.10.15 |
재로드 및 #해킹 없이 윈도우 위치를 변경할 수 있는 방법은? (0) | 2023.10.15 |