作业:
Training4:字符串训练
1、题目: 请编写一个C函数,该函数将一个字符串逆序
#include <stdio.h>
#include <string.h>
char *reserve(char *s)
{
int i;
int n = strlen(s)/2;
char tmp;
for(i = 0; i <= n; i++)
{
tmp = s[i];
s[i] = s[strlen(s)-i-1];
s[strlen(s)-i-1] = tmp;
}
return s;
}
int main()
{
char str[20];
printf("Please input a string:\n");
scanf("%s", str);
printf("\nThe reserved string is:\n%s\n", reserve(str));
return 0;
}
2、题目: 请编写一个C函数,该函数可以实现将一个整数转为任意进制的字符串输出
#include <stdio.h>
void to_change(int num,int n);
int main()
{
int num,n;
printf("Please enter a number to change:");
scanf("%d",&num);
printf("请输入要转换的进制: ");
scanf("%d",&n);
to_change(num,n);
printf("\n");
return 0;
}
void to_change(int num,int n)
{
int r;
r = num % n;
if(num > 0)
to_change( num / n,n );
putchar( '0' + r);
return ;
}
3、题目: 输入一个字符串,计算字符串中子串出现的次字数
#include <stdio.h>
#include <string.h>
void main()
{
char str1[20], str2[20], *p1, *p2;
int sum=0;
printf("Please enter two strings\n");
scanf("%s%s", str1, str2);
p1=str1;
p2=str2;
while(*p1 != '\0')
{
if(*p1 == *p2)
{
while(*p1 == *p2 && *p2 != '\0')
{
p1++;
p2++;
}
}
else
p1++;
if(*p2 == '\0')
sum++;
p2=str2;
}
printf("%d", sum);
getchar();
}
4、题目: 编写一个C函数,将”I am from shanghai ”倒置为”shanghai from am I”,即将句子中的单词位置倒置,而不改变单词内部结构.
#include <stdio.h>
#include <string.h>
void change(char str[], int n)
{
int i, j;
char temp;
for(i = 0,j = n;i < n / 2;i++,j--)
{
temp = str[i];
str[i] = str[j - 1];
str[j - 1] = temp;
}
}
void re_change(char *s)
{
int count = 0;
while(1)
{
count++;
if((*s) == ' ' || (*s) == '\0')
{
change(s - (count - 1), count - 1);
count = 0;
}
s++;
if(*s == '\0')
{
break;
}
}
}
int main()
{
char s[] = "I am from shanghai";
int size = 0;
size = strlen(s);
change(s, size);
re_change(s);
puts(s);
return 0;
}
5、题目: 输入一个字符串,同时输入帧头和帧尾(可以是多个字符),将该字符串中合法的帧识别出来.提示:帧头和帧尾分别是head和tail 字符串”asdheadhauboisoktail”中headhauboisoktail是合法帧
#include <stdio.h>
#include <string.h>
int substr(char str[255],char s[255],int k);
int main()
{
char str[255];
char head[255];
char tail[255];
int x,y;
int i = 0,t;
printf("enter a string:\n");
scanf("%s",str);
printf("enter head:\n");
scanf("%s",head);
printf("enter tail:\n");
scanf("%s",tail);
t = substr(str,head,0);
x = t - strlen(head);
y = substr(str,tail,t);
for(i = x;i < y;i++)
{
printf("%c",str[i]);
}
printf("\n");
return 0;
}
int substr(char str[255],char s[255],int k)
{
char *p = str+k;
char *p1 = s;
int i = k;
int flag = 0,m;
while(*p != '\0')
{
if(*p == *p1 && flag == 0)
{
while(*p == *p1 && *p1 != '\0')
{
p++;
p1++;
i++;
}
if(*p1 == '\0')
{
flag = 1;
m = i;
}
}
else
{
p++;
i++;
}
}
return m;
}