programing

C 문자열 내의 문자의 인덱스를 찾으려면 어떻게 해야 합니까?

goodcopy 2022. 8. 10. 00:19
반응형

C 문자열 내의 문자의 인덱스를 찾으려면 어떻게 해야 합니까?

이 합니다."qwerty"그리고 나는 그 인덱스 위치를 찾고 싶다.e는 ()가 됩니다.2)

C에서는 어떻게 하죠?

strchr인덱스가 아닌 문자로 포인터를 반환합니다.

strchr이 반환하는 문자열 주소에서 스트링 주소를 빼면 됩니다.

char *string = "qwerty";
char *e;
int index;

e = strchr(string, 'e');
index = (int)(e - string);

결과는 0을 기준으로 하므로 위의 예에서는 2가 됩니다.

이것으로 충분합니다.

//Returns the index of the first occurence of char c in char* string. If not found -1 is returned.
int get_index(char* string, char c) {
    char *e = strchr(string, c);
    if (e == NULL) {
        return -1;
    }
    return (int)(e - string);
}

이 경우에도 하실 수 있습니다.strcspn(string, "e")하지만 여러 개의 문자를 검색할 수 있기 때문에 속도가 훨씬 느릴 수 있습니다.「」를 사용합니다.strchr포인터를 빼는 것이 가장 좋은 방법입니다.

void myFunc(char* str, char c)
{
    char* ptr;
    int index;

    ptr = strchr(str, c);
    if (ptr == NULL)
    {
        printf("Character not found\n");
        return;
    }

    index = ptr - str;

    printf("The index is %d\n", index);
    ASSERT(str[index] == c);  // Verify that the character at index is the one we want.
}

이 코드는 현재 테스트되지 않았지만 올바른 개념을 보여줍니다.

그럼 어떻게 되는 거죠?

char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;

원래 문자열을 보존하기 위해 e에 복사하는 경우, 신경 쓰지 않으면 *string을 사용하여 조작할 수 있습니다.

언급URL : https://stackoverflow.com/questions/3217629/how-do-i-find-the-index-of-a-character-within-a-string-in-c

반응형