练习2-4
#include <stdio.h>
#define MAXLINE 1000 //maximun of amount of array
//2-4
void Squeeze(char s1[], char s2[]);
int main() {
char s1[MAXLINE];//array s1
char s2[MAXLINE];//array s2
int c;
int length_s1 = 0;//memory the length of array s1
int length_s2 = 0;//memory the length of array s1
for (int i=0; i < MAXLINE - 1 && (c = getchar()) != EOF; ++i) {//input array s1
s1[i] = c;
length_s1++;
}
s1[length_s1] = '\0';//set the final array element as empty
printf("the process of input of s1 completed\n");
for (int i=0; i < MAXLINE - 1 && (c = getchar()) != EOF; ++i) {//input array s2
s2[i] = c;
length_s2++;
}
s2[length_s2] = '\0';//set the final array element as empty
printf("the process of input of s2 completed\n");
Squeeze(s1, s2);
}
void Squeeze(char s1[], char s2[]) {
int i = 0;
int j = 0;
while (s1[i] != '\0' && s2[j] != '\0') {//scan array s1 and array s2
if (s1[i] == s2[j]) {
for(int k=i; s1[k] != '\0'; ++k) {
s1[k] = s1[k+1];//delete the common element from array s1
}
++j;//set the location of array s1 as the same location of orignal array s1
}
i++;
j++;
}
printf("the new s1 :%s\n", s1);
}
练习2-5
#include <stdio.h>
#define MAXLINE 1000 //maximun of amount of array
//2-5
int Any(char s1[], char s2[]);
int main() {
char s1[MAXLINE];//array s1
char s2[MAXLINE];//array s2
int c;//input label
int length_s1 = 0;//memory the length of array s1
int length_s2 = 0;//memory the length of array s2
int location;//return location
for (int i=0; i < MAXLINE - 1 && (c = getchar()) != EOF; ++i) {//input array s1
s1[i] = c;
length_s1++;
}
s1[length_s1] = '\0';//set the final array element as empty
printf("the process of input of s1 completed\n");
for (int i=0; i < MAXLINE - 1 && (c = getchar()) != EOF; ++i) {//input array s2
s2[i] = c;
length_s2++;
}
s2[length_s2] = '\0';//set the final array element as empty
printf("the process of input of s2 completed\n");
location = Any(s1, s2);
printf("the location is %d", location);
}
int Any(char s1[], char s2[]) {
int i = 0;
int j = 0;
printf("s1 : %s", s1);
printf("s2 : %s", s2);
while (s2[i] != '\0') {//scan array s1 and array s2
while(s1[j] != '\0') {
if(s2[i] != s1[j]) ++j;//search the same element in array s2
else return j+1;
}
++i;
}
return -1;
}
练习2-9
#include <stdio.h>
int bitcount(unsigned int x) {
int bitcount_ = 0;
if(x > 0) {//when x > 0, then exist one single digit "one" in x at least
bitcount_ = 1;
while ((x &= (x - 1)) != 0) ++bitcount_;//plus one when x decrean
}
return bitcount_;
}
int main() {
int count = 0;
unsigned int x_ = 7;
count = bitcount(x_);
printf("%d\n", count);
}
练习2-10
#include <stdio.h>
//2-10
int lower(int c_) {
return c_ = (c_ >= 'A' && c_ <= 'Z') ? (c_ + 'a' - 'A') : c_;
}
int main() {
int c;
int uppercase_c = 0;
if ((c = getchar()) != EOF) {
uppercase_c = lower(c);
}
putchar(uppercase_c);
return 0;
}