sourcecode

String.indexOf 함수 C

copyscript 2023. 6. 28. 21:54
반응형

String.indexOf 함수 C

문자열에 있는 문자의 인덱스를 반환하는 C 라이브러리 함수가 있습니까?

지금까지 찾은 것은 원래 문자열에 있는 위치가 아니라 찾은 char *를 반환하는 strt와 같은 함수들뿐입니다.

strstr포인터를 찾은 문자로 반환하므로 포인터 산술을 사용할 수 있습니다. (참고: 이 코드는 컴파일 능력에 대해 테스트되지 않았으며 유사 코드에서 한 단계 떨어져 있습니다.)

char * source = "test string";         /* assume source address is */
                                       /* 0x10 for example */
char * found = strstr( source, "in" ); /* should return 0x18 */
if (found != NULL)                     /* strstr returns NULL if item not found */
{
  int index = found - source;          /* index is 8 */
                                       /* source[8] gets you "i" */
}

나는 생각합니다.

size_t strcspn (const char * str1, const char * str2 );

당신이 원하는 것입니다.여기서 발췌한 예는 다음과 같습니다.

/* strcspn example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "fcba73";
  char keys[] = "1234567890";
  int i;
  i = strcspn (str,keys);
  printf ("The first number in str is at position %d.\n",i+1);
  return 0;
}

편집: strchr은 한 문자에 대해서만 더 좋습니다.포인터 산술은 "안녕하세요!"라고 말합니다.

char *pos = strchr (myString, '#');
int pos = pos ? pos - myString : -1;

중요: strchr()은 문자열이 없으면 NULL을 반환합니다.

strstr을 사용하여 원하는 것을 달성할 수 있습니다.예:

char *a = "Hello World!";
char *b = strstr(a, "World");

int position = b - a;

printf("the offset is %i\n", position);

결과는 다음과 같습니다.

the offset is 6

만약 당신이 순수한 C에 완전히 얽매이지 않고 문자열을 사용할 수 있다면, strchr()이 있습니다.

당신 자신의 것을 쓰세요.

C용 BSD 라이센스 문자열 처리 라이브러리의 코드, zString

https://github.com/fnoyanisi/zString

int zstring_search_chr(char *token,char s){
    if (!token || s=='\0')
        return 0;

    for (;*token; token++)
        if (*token == s)
            return 1;

    return 0;
}

쓸 수 있습니다.

s="bvbrburbhlkvp";
int index=strstr(&s,"h")-&s;

의 색인을 구하다'h'주어진 잡담 속에서

언급URL : https://stackoverflow.com/questions/4824/string-indexof-function-in-c

반응형