第7讲 指针与数组 单元作业

1. 利用字符指针将输入的一个字符串中的大小写字母相互转换,并输出转换后的字符串的内容。如,假设输入的字符串的内容为“How are you”,则转换后的内容为“hOW ARE YOU”。

 

YZY.ver:

 

 1 #include <iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     char s[100];
 6     puts(s);
 7     char *p=s;
 8     cout<<"大小写转换!";
 9     while(*p!='\0')
10     {
11         if (*p >= 'a' && *p <= 'z')
12             *p = *p - 'a' + 'A';
13         else if(*p >= 'A' && *p <= 'Z')
14             *p = *p - 'A' + 'a';
15         p++;
16     }
17     cout<<s<<endl;
18     system("pause");
19     return 0;
20 }
View Code

 

2. 

利用字符指针将字符串s中从第n个字符开始的内容复制到字符串t中。

 1 #include <iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     char s[100],t[100];
 6     int n;
 7     cin>>s;
 8     cout<<"从第几个字符开始复制?"<<endl;
 9     cin>>n;
10     char *p=s;
11     char *q=t;
12     while(*p)
13     {
14         *q=*(p+n-1);
15         q++;
16         p++;
17     }
18     cout<<t<<endl;
19     system("pause");
20     return 0;
21 }
View Code

 

3. 利用指针将一个包含10个整数的数组中的最大最小元素进行交换,并输出交换后的内容。10个整数为随机产生的0~100之间的数。(若最大最小元素不唯一,则交换任意两个都算正确,即可以不用特殊考虑不唯一的情况)。

 

 1 #include <iostream>
 2 #include <ctime>
 3 using namespace std;
 4 int main()
 5 {
 6     int const N=10;
 7     int a[N];
 8     srand(time(0));
 9     cout<<"十个数字依次为:"<<endl;
10     for (int i=0;i<N;i++)
11        {
12         a[i]=rand()%101;
13         cout<<a[i]<<" ";
14     }
15     cout<<endl;
16     int *max=a,*min=a;
17     for (int i=1;i<N;i++)
18        {
19         if (a[i]>*max)
20               {
21             max=&a[i];
22         }
23         if (a[i]<*min)
24               {
25             min=&a[i];
26         }
27     }
28      cout<<"最大数为:"<<*max<<"  "<<"最小数为:"<<*min<<endl;
29     // 交换最大值和最小值
30     int t=*max;
31     *max=*min;
32     *min=t;
33     cout<<"交换后的数组为:"<<endl;
34     for (int i=0;i<N;i++)
35        {
36         cout<<a[i]<<" ";
37     }
38     cout<<endl;
39        system("pause");
40     return 0;
41 }
View Code

 

4. 利用字符指针将一串字符倒序存放后输出。例如原数组a的内容为“VISUAL C++PROGRAM”,倒序后数组a中的内容为“MAGORP++C LASUIV”。

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 int main()
 5 {
 6 char a[100],b[100];
 7 cout<<"请输入字符内容a:"<<endl;
 8 gets(a);
 9 int l=strlen(a);
10 char *p=a;
11 char *q=b;
12 q=&b[l-1];
13 b[l]='\0';
14 while (*p!='\0')
15        *q--=*p++;
16 cout<<"转换完成后的结果为:"<<endl;
17 puts(b);
18 system("pause");
19 return 0;
20 }
View Code

 

 
posted @ 2023-11-18 13:56  YANTARES  阅读(56)  评论(0)    收藏  举报