问题12_1
函数 f u n fun fun 的功能是:把形参 s s ss ss 所指字符串数组中,删除所有串长超过 k k k 的字符串,函数返回剩余字符串的个数。 s s ss ss 所指字符串数组中共有 N N N 个字符串,且串小于 M M M。
代码12_1
#include<stdio.h>
#include<string.h>
#define N 5
#define M 10
int fun(char (*ss)[M], int k){
int i, j=0, len;
for(i=0; i<N; i++){
len = strlen(ss[i]);
if(len<=k)
strcpy(ss[j++], ss[i]);
}
return j;
}
void main(void){
char x[N][M] = {"Beijing", "Shanghai", "Tianjin", "Nanjing", "Wuhan"};
int i, f;
printf("\nThe original string\n\n");
for(i=0; i<N; i++)
puts(x[i]);
printf("\n");
f = fun(x, 7);
printf("The string witch length is less than or equal to 7:\n");
for(i=0; i<f; i++)
puts(x[i]);
printf("\n");
}
结果12_1
问题12_2
函数
f
u
n
fun
fun的功能是:逐个比较
p
p
p、
q
q
q 所指两个字符串对应位置上的字符,并把
A
S
C
I
I
ASCII
ASCII 值大或相等的字符依次存放到
c
c
c 所指的数组中,形成一个新的字符串。
例如,若主函数中
a
a
a 字符串为
a
B
C
D
e
F
g
H
"
aBCDeFgH"
aBCDeFgH" ,
b
b
b 字符串为
A
B
c
d
ABcd
ABcd ,则
c
c
c 中的字符串中应为
"
a
B
c
d
e
F
g
H
"
"aBcdeFgH"
"aBcdeFgH" 。
代码12_2
#include<stdio.h>
#include<string.h>
void fun(char *p, char *q, char *c){
int k=0;
while(*p||*q){
if(*p<*q)
c[k] = *q;
else c[k] = *p;
if(*p) p++;
if(*q) q++;
k++;
}
}
void main(void){
char a[10] = "aBCDeFgH", b[10]="ABcd", c[80] = {'\0'};
fun(a, b, c);
printf("The string a:"), puts(a);
printf("The string b:"), puts(b);
printf("The result :"), puts(c);
}
结果12_2
问题12_3
规定输入的字符串中只包含字母和
∗
*
∗ 号。请编写函数
f
u
n
fun
fun ,其功能是:除了字符串前导的
∗
*
∗ 号之外,将串中其他
∗
*
∗ 全部删除。在编写函数时,不得使用
C
C
C 语言提供的字符串函数。
例如,字符串的内容为
"
∗
∗
∗
∗
A
∗
B
C
∗
∗
∗
D
E
F
∗
∗
G
∗
∗
∗
∗
∗
"
"****A*BC***DEF**G*****"
"∗∗∗∗A∗BC∗∗∗DEF∗∗G∗∗∗∗∗" ,删除后,字符串的内容应当是
"
∗
∗
∗
∗
A
B
C
D
E
F
G
"
"****ABCDEFG"
"∗∗∗∗ABCDEFG" 。
代码12_3
#include<string.h>
#include<stdio.h>
#include<conio.h>
void fun(char *a){
int i=0;
char *p=a;
/* 单出处理字符串前缀为'*'的情况 */
while(*p && *p=='*'){
a[i] = *p;
i++;
p++;
}
/* 循环判断当前指向的字符是否'*'如果不是保存 */
while(*p){
if(*p!='*'){
a[i] = *p;
i++;
}
p++;
}
a[i] = '\0';
}
void main(void){
char s[80];
printf("Enter a string:\n");
gets(s);
fun(s);
printf("The string after deleted:\n");
puts(s);
}