1、改错:
(a)、void test1()
{
char string[10]; //char string[11]
char *str1 = "0123456789";
strcpy(string, str1);
}
//str1字符串为0~9十个字符加一个\0,所以需要一个十一个字节。
(b)、void test2()
{
char string[10], str1[10];
//int i = 0;
for (i=0; i<10; i++) //未定义i的类型
{
str1[i] = 'A';
}
strcpy(string, str1);
}
(c)、void test3(char *str) //void test3(char *str1)
{
char string[10];
if (strlen(str1)<=10)
{
strcpy(string, str1);
}
}
2、找赛手:2个羽毛球队比赛,各出3人,每个人只比一次。甲队为A,B,C三人,乙队为X,Y,Z三人。有人打听比赛名单,A说他不和X比,C说不和X,Z比。编程找出三队赛手的名单.
#include <stdio.h>
void main(void)
{
printf("不会\n");
}
3、用C语言实现字符串中子字符串的替换, 成功返回0,失败返回-1.例如:“ABCDEFG”这个字符串,把其中”BCD”替换成“9527”这个子串,结果变成:“A9527EFG”
函数原型:
int str_replace(char str, char replaced_str, char *new_str)
//未完待续
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int replace(char *replaced_str, char *new_str, int len);
int str_replace(char *str, char * replaced_str, char *new_str);
void main(void)
{
char str1[10] = "ABCDEFG", *str2 = "CDE", *str3 = "1234";
int a = str_replace(str1, str2, str3);
// printf("%d\n", a);
// printf("ok\n");
printf("%s", str1);
return;
}
int str_replace(char *str, char * replaced_str, char *new_str)
{
int i = 0, j = 0, len = strlen(replaced_str), q = 0;
// int *p = (int *)malloc(strlen(str)/len);
// printf("%d\n", len);
for (i=0; str[i]; i++)
{
if (str[i] == replaced_str[0])
{
for (j=0; j<len; j++)
{
if (str[i+j] != replaced_str[j])
{
break;
}
}
if (j == len)
{
// printf("ok\n");
printf("%c\n", str[i]);
q = replace(&str[i], new_str, len);
}
// printf("ok\n"); no
}
}
// printf("%d\n", i);
return q;
}
int replace(char *replaced_str, char *new_str, int len)
{
int i = 0, j = 0, q = 0;
// printf("ok\n");
q = len - strlen(new_str);
if (0 == q) //新字符串与被替换字符串等长
{
for (i=0; i<strlen(new_str); i++)
{
replaced_str[i] = new_str[i];
}
}
else if (q > 0) //新字符串更短
{
for (i=0; i<strlen(new_str); i++)
{
replaced_str[i] = new_str[i];
}
for (i; replaced_str[i+q]; i++)
{
replaced_str[i] = replaced_str[i+q];
}
replaced_str[i] = 0;
}
else //新字符串更长
{
// printf("ok\n");
char *p = replaced_str;
//printf("ok\n");
int len = strlen(replaced_str);
replaced_str += strlen(replaced_str);
replaced_str--;
printf("%c\n", *replaced_str);
// while(++replaced_str);
replaced_str = replaced_str - q; //q是负的
int w = 0;
printf("%c\n", *replaced_str); //
while(w < len)
{
*replaced_str = *(replaced_str - q); ///
replaced_str -= 1;
w++;
}
//printf("ok\n");
for (i=0; i<strlen(new_str); i++)
{
printf ("%c = ", *(p+i));
*(p+i)= new_str[i];
printf ("%c\n", (*p));
}
//printf("ok\n");
}
return 1;
}