定义一个函数 char dtake(char str[],int m),求str串从右开始数的第m个字符

题目如下:

编程要求

1.定义函数char dtake(char str[],int m),求串str的从右数第m个字符。
2.定义主函数,实现:

(1)输入串str;

(2)输入m的值;

(3)调用dtake函数;

(4)输出调用结果。

测试说明

平台会对你编写的代码进行测试,若是与预期输出相同,则算通关。 样例输入: 12345 1 The value of the 1th character from the right of 12345 is 5

针对这一道题,我们可以通过将数组进行倒转来解决:

2021.10.23重新做了改动,运用的指针变量不熟练导致不能输出数字的行数。

#include <stdio.h>
#include <string.h>
#define  N   10
char dtake(char s[],int m,int i)
{  
   char a;
   a=s[i-m];  
    return a;
}
void main()
{  
	char str[N],t;
	int m,i=0,j;

    while((str[i]=getchar())!='\n')
	i++;
	scanf("%d",&m);
	t=dtake(str,m,i);   
	printf("The value of the %dth character from the right of ",m);
	for(j=0;j<i;j++)
	printf("%c",str[j]);
	printf(" is %c",t);
	return 0;
}

这是答案的方法:

include <stdio.h>
include <string.h>
define N 10
char dtake(char str[],int m)
{
    char  c;
    c=str[strlen(str)-m];
    return c;
}
void main()
{
    char str[N],t;
    int m;
    //printf("please input num:");
    scanf("%s",str);
    //printf("please input  the num's position that you want to take:");
    scanf("%d",&m);
    t=dtake(str,m);
    printf("The value of the %dth character from the right of %s is %c\n",m,str,t);
}

作者码字不易,给个赞坚持下去。

猜你喜欢

转载自blog.csdn.net/qq_46069852/article/details/120700778