c언어

C언어 - 특정 글자 지우고 단어 반대로 출력하기

pi92 2021. 3. 4. 08:45
#include<stdio.h>
#include<string.h> // strlen 함수
#include<stdlib.h> // malloc 함수

char* revsqueeze(char *, char);

int main()
{


	char i=0;
	char c;
	char s[30];
	char* result;

	printf("입력 값 :");
	while ((s[i++] = getchar()) != '\n');  // 단어를 입력하는 반복문
	s[--i] = '\0';

	printf("\n제외 할 글자");
	c = getchar();

	result = revsqueeze(s, c);  // 특정 단어를 지우고 반대로 출력하는 함수

	printf("%s\n", result);

	free(result);

	return 0;


}

char* revsqueeze(char *s, char c) {

	int i;
	int j = 0;
	char* ps = s;
	char *temp;
	temp = (char*)malloc(strlen(ps) + 1);   // temp에 할당량 주기

	i = strlen(ps); // 글자길이 구하기
	ps = ps + i - 1; // 마지막 글자 주소로 가기


	while (i-- != 0) {  //  temp에 특정 단어(c)를 제외하고 뒤에서부터 입력하기
		if (*ps == c) {
			ps--;
		}
		else {
			*temp = *ps;
			ps--;
			temp++;
			j++;
		}
	}
	*temp = '\0'; // 마지막에 null 값 입력하기
	temp = temp - j; // 단어의 맨 앞 주소로 이동하기

	return temp;

}