实验7-3-1 字符串逆序 (15分)
输入一个字符串,对该字符串进行逆序,输出逆序后的字符串。
输入格式:
输入在一行中给出一个不超过80个字符长度的、以回车结束的非空字符串。
输出格式:
在一行中输出逆序后的字符串。
输入样例:
Hello World!
输出样例:
!dlroW olleH
//定义一个字符串数组;
#include<stdio.h>
#include<string.h>
int main(){
char str[81];
//定义一个字符串数组;空间大小为81;字符串数组的定义,一定要定义空间;
int i=0;
int c;
//getchar是从数组中扣下每一个字符,一直循环到扣下的是'\n'为止;
//强制转换c为char变量等于str[]中,
while((c=getchar())!='\n'){
str[i]=(char)c;
i++;
}
i--;
//上面的i循环到哪个,这里的i就从上面的i-1开始逆向输出;
for(;i>=0;i--){
printf("%c",str[i]);
}
return 0;
}
#include<stdio.h>
int main()
{
int i, j;
char ch, a[80];
ch=getchar();
for(i=0; ch!='\n'; i++){
a[i]=ch;
ch=getchar();
}
i--;
for(;i>=0;i--){
printf("%c",a[i]);
}
return 0;
}
实验7-3-2 查找指定字符 (15分)
本题要求编写程序,从给定字符串中查找某指定的字符。
输入格式:
输入的第一行是一个待查找的字符。第二行是一个以回车结束的非空字符串(不超过80个字符)。
输出格式:
如果找到,在一行内按照格式“index = 下标”输出该字符在字符串中所对应的最大下标(下标从0开始);否则输出"Not Found"。
输入样例1:
m
programming
输出样例1:
index = 7
输入样例2:
a
1234
输出样例2:
Not Found
#include<stdio.h>
#include<string.h>
int main(){
char x;
scanf("%c\n",&x); //在这里的\n
char str[80];
int i=0;
int index=-1;
int cnt=0;
char ch=getchar();
for(i=0;ch!='\n';i++){ //向str[]数组中输入元素;在这里的\n
str[i]=ch;
cnt++;
ch=getchar();
}
//这里的for循环写上花括号,则每条的语句命令的结果都会执行出来;
for(i=0;i<cnt;i++){
if(x==str[i]){
index=i;
}
if(index!=-1){
printf("index=%d",index);
}else
printf("not found");
}
return 0;
}
m
programming
not found
not found
not found
not found
not found
not found
index=6
index=7
index=7
index=7
index=7
Program ended with exit code: 0
如果不加花括号,则表现出来最后一天命令的执行语句;
for(i=0;i<cnt;i++)
if(x==str[i]){
index=i;
}
if(index!=-1){
printf("index=%d",index);
}else
printf("not found");
m
programming
index=7
Program ended with exit code: 0
#include<stdio.h>
int main(){
char x; int i;
int count = 0;
for (i = 0; i < 5; i++)
count++;
printf("The value of count is: %d\n", count);
return 0;
}
The value of count is: 5
Program ended with exit code: 0
#include<stdio.h>
#define N 80
//思路:注意输入的格式,第一个字符使用scanf读入一个字符,而且请添加一个\n
// 否则将会出现错误。继续使用getchar的方式进行读入字符。也可以使用
// scanf读入字符串,再使用strlen测得字符串长度,然后依次遍历。
int main()
{
int i, index = -1, cnt = 0;
char c, ch; //c是单个字符,ch是字符数组每次读入的字符
char string[N] = { 0 };
scanf("%c\n",&c); //这操作好强啊!!! 为什么必须要加上 \n
//读入字符串:方式一
ch = getchar();
for(i = 0; ch != '\n'; i++)
{
string[i] = ch;
cnt++;
ch = getchar();
}
/* 读入字符串:方式二
scanf("%s", string);
len = strlen(string);
*/
for (i = 0; i < cnt; i++)
{
if (c == string[i])
{
index = i;
}
}
if (index != -1)
{
printf("index = %d\n", index);
}
else
{
printf("Not Found\n");
}
return 0;
}
```c
#include<stdio.h>
#include<string.h>
int main(){
char str[20];
char x;
scanf("%c\n",&x);
scanf("%s",str); //这里不需要使用取地址符;
int i;
int index=-1;
int n=strlen(str);
for(i=0;i<n;i++)
if(x==str[i]){
index=i;
}
if(index==-1){
printf("not found\n");
}else
printf("index=%d\n",index);
return 0;
}