编写程序,输入一字符串,输出指定字符在字符串中出现的位置和次数;如果该字符串中不包含指定字符,输出相应的提示信息。
例如:字符串aevdbcg中字符b出现的位置为4,次数为1;
字符串aaaab中字符a出现的位置为0,1,2,3,次数为4
编程提示:
(1)定义两个一维数组,一个字符数组用来存放字符串,一个整型数组用来存放指定字符出现的为位置。
(2)定义一个标志量flag初始化为0,用来记录字符串中是否有指定字符。
(3)依次访问字符串中的字符和指定字符作比较,如果相同就把下标存入整型数组,并置flag为1。
说明:
(1)输入格式:getchar(),gets()
(2)提示性文字输出格式:"input a charactor and a string:"
输出格式:"number=%d\npositions are:"
"%5d"
"no charactor %c\n"
#include<stdio.h> int main() { int s1[50] = { 0 }; char s2[50] = { 0 }; int flag = 0,count=0; printf("input a charactor and a string:"); char ret = getchar(); gets_s(s2); for (int i = 0; s2[i] != '\0'; i++) { if (s2[i] == ret) { s1[count] = i; count++; flag = 1; } } if (flag == 0) printf("no charactor %c\n",ret); if (flag == 1) { printf("number=%d\npositions are:", count); for (int i = 0; i < count; i++) { printf("%5d", s1[i]); } } return 0; }