에 포함 된 모든 문자를 검사 isalpha()
기능을 사용할 수 있습니다. 이해를 위해서 먼저 간단한 버전 :
// header needed for isalpha()
#include <ctype.h>
void condense_alpha_str(char *str) {
int source = 0; // index of copy source
int dest = 0; // index of copy destination
// loop until original end of str reached
while (str[source] != '\0') {
if (isalpha(str[source])) {
// keep only chars matching isalpha()
str[dest] = str[source];
++dest;
}
++source; // advance source always, wether char was copied or not
}
str[dest] = '\0'; // add new terminating 0 byte, in case string got shorter
}
그것은, isalpha()
테스트와 일치하는 문자를 복사 건너 뛰는 때문에하지 않는 사람들을 제거, 현재 위치에서 문자열을 통해 이동합니다. 코드를 이해하려면 C 문자열이 단지 char
배열이고 바이트 값 0이 문자열의 끝을 표시한다는 사실을 깨닫는 것이 중요합니다. 또 다른 중요한 세부 사항은 C 배열과 포인터가 여러 가지 (전부는 아님!) 방법으로 동일하다는 것입니다. 따라서 포인터는 배열과 마찬가지로 색인을 생성 할 수 있습니다. 또한이 간단한 버전은 문자열이 실제로 변경되지 않는 경우에도 문자열의 모든 바이트를 다시 쓰게됩니다.
그런 다음 전용 메모리를 할 것 매개 변수로 전달 필터 기능을 사용하여,보다 완벽한 기능을 갖춘 버전, str을 변경하는 경우, 기록 및 대부분의 라이브러리 문자열 함수와 같은 str
에 대한 포인터를 반환하는 것은 수행
char *condense_str(char *str, int (*filter)(int)) {
int source = 0; // index of character to copy
// optimization: skip initial matching chars
while (filter(str[source])) {
++source;
}
// source is now index if first non-matching char or end-of-string
// optimization: only do condense loop if not at end of str yet
if (str[source]) { // '\0' is same as false in C
// start condensing the string from first non-matching char
int dest = source; // index of copy destination
do {
if (filter(str[source])) {
// keep only chars matching given filter function
str[dest] = str[source];
++dest;
}
++source; // advance source always, wether char was copied or not
} while (str[source]);
str[dest] = '\0'; // add terminating 0 byte to match condenced string
}
// follow convention of strcpy, strcat etc, and return the string
return str;
}
예 필터 함수 :
int isNotAlpha(char ch) {
return !isalpha(ch);
}
예 호출
char sample[] = "1234abc";
condense_str(sample, isalpha); // use a library function from ctype.h
// note: return value ignored, it's just convenience not needed here
// sample is now "abc"
condense_str(sample, isNotAlpha); // use custom function
// sample is now "", empty
// fscanf code from question, with buffer overrun prevention
char x[100];
while (fscanf(inputFile, "%99s", x) == 1) {
condense_str(x, isalpha); // x modified in-place
...
}
참조 :
읽기 int isalpha (int c); 수동 : C는 알파벳 문자인지
확인합니다.
반환 값 :
실제로 c가 알파벳 문자 인 경우 0과 다른 값 (즉, true)입니다. 0 일 경우 (즉, 거짓)
'난 것이 잠재적 인 버퍼 오버런입니다. 'char x [100]'을 가지고있을 때 항상 예를 들어'fscanf (inputFile, "% 99s", x)'를 사용해야합니다. – hyde