개인 공부/알고리즘&자료구조
[자료구조] 자료구조 수업 과제 1
코딩하는 해달
2022. 11. 19. 19:48
자료구조 수업때 과제를 하며 공부한 기록을 남긴다.
[과제 1]
1.배열 활용하기
공백문자들이 문장의 앞, 중간, 뒤에 포함되어있는 스트링이 입력될 때 스트링의 문자 개 수 를 계산하여 다음과 같이 출력하라. (단, 단어 사이에 두개이상의 연속된 공백 문자들은 하나의 공백 문자로 대체)
*출력결과
> hello
hello: 5
> welcome to the class
welcome to the class: 20
> programming is fun, right?
programming is fun, right?
언어는 자신이 원하는 언어로 작성해도 좋습니다.
=================================================================================
나는 c언어를 이용해서 과제를 해결해보았다.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
while (1) {
char a[100] = "";
char str[100] = "";
int size = 1;
int pull = 0;
gets_s(str, sizeof(str));
a[0] = str[0];
for (int i = 1; str[i] != '\0'; i++) {
if (str[i] == ' ') {
if (str[i - 1] == ' ') {
pull++;
continue;
}
else {
size++;
a[i - pull] = str[i];
}
}
else {
size++;
a[i - pull] = str[i];
}
}
if (a[size - 1] == ' ') {
a[size - 1] = '\0';
size--;
}
if (a[0] == ' ') {
for (int i = 1; i < size; i++) {
a[i - 1] = a[i];
}
a[size - 1] = '\0';
size--;
}
printf("%s: %d\n", a, size);
}
return 0;
}
[출력결과]
반응형