编写程序实现功能用户从键盘输入一行字符,分别统计出其英文字母和数字字符的个数
一、编写程序实现功能:用户从键盘输入一行字符,分别统计出其英文字母和数字字符的个数
代码如下:
s=input(“请输入一行字符:
alpha,num,space,other=0,0,0,0
for i in s:
if i.isalpha():
alpha+=1
elif i.isdigit():
num+=1
elif i.isspace():
space+=1
else:
other+=1
print(‘英文字符数{},数字字符数{},空格字符数{},其他字符数{}’.format(alpha,num,space,other))
扩展资料
字符串的函数应用:
1、连接运算 concat(s1,s2,s3…sn) 相当于s1+s2+s3+…+sn.
例:concat(‘11’,‘aa’)=‘11aa’;
2、求子串。 Copy(s,I,I) 从字符串s中截取第I个字符开始后的长度为l的子串。
例:copy(‘abdag’,2,3)=’bda’
3、删除子串。过程 Delete(s,I,l) 从字符串s中删除第I个字符开始后的长度为l的子串。
例:s:=’abcde’;delete(s,2,3);结果s:=’ae’
4、插入子串。 过程Insert(s1,s2,I) 把s1插入到s2的第I个位置
例:s:=abc;insert(‘12’,s,2);结果s:=’a12bc’
5、求字符串长度 length(s) 例:length(‘12abc’)=5
在ASP中 求字符串长度用 len(s)例: len(“abc12”)=5
6、搜索子串的位置 pos(s1,s2) 如果s1是s2的子串 ,则返回s1的第一个字符在s2中的位置,若不是子串,则返回0.
例:pos(‘ab’,’12abcd’)=3

二、编写函数insert(s1,s2,pos),实现在字符串s1中的指定位置pos处插入字符串s2。要求利用指针编写程序。
这是你多写了一句putchar(pos)造成的。
把它去了就行。还有,怎么插入到pos位置,常规理解是插入到此字符之间啊?
#include
#include
void insert(char *p1,char p2,char pos)
{
int m,n,i;
char temp[40];
m=strlen(p1);
n=strlen(p2);
for(i=0;i { if(pos==(p1+i)) { strcpy(temp,p1+i); *(p1+i)=’\0’; strcat(p1,p2); strcat(p1,temp); puts(p1); break; } } } void main() { char s1[20], s2[20]; char pos; printf(“Please input s1:”); gets(s1); printf(“Please input s2:”); gets(s2); printf(“Please input pos:”); pos=getchar(); insert(s1,s2,pos); }
三、c语言insert函数?
C语言insert函数实现在字符串的内部增加字符串。void insert(char * s1,char * s2, int n);将s2指向的字符串的拷贝,添加到s1第n个字符的位置,原位置的字符后移。n=0时,s2增加到s1的首部;n=s1的字符串长度时,s2增加到s1的末尾。
注意:使用空格字符来表示字符串的结束。例如source指向位置,依次保存了字符’a’,字符’b’,字符空格’ ‘,字符’c’,则source指向的字符串为”ab”。
保存为functions.cpp。遇到异常情况,输出”error”;否则不要随意输出,会视为错误。
下面是相关代码:
#include #include
void insert(char * s1,char * s2,int n){int i = 0;int k = 0;int j = 0;int m = 0;char s3[100] = {0};if(n < 0 || s1 == NULL || s2 == NULL)//判定{printf(“error”);return;}for (j = 0; s1[j] != ’ ’ && s1[j] != ‘\0’; j++);//得出传进来的s1的长度jfor (k = 0; s2[k] != ’ ’ && s2[k] != ‘\0’; k++);//得出传进来的s2的长度kif(n > j)//当然,第n个字符的位置不可能大于s1的长度j{printf(“error”);return;}else{for (i = n, m = 0;i < k; i++, m++)//这里是将s1 n个字符后的字符赋给s3{*(s3+m) = (s1 + i);}for (i = n,m = 0; m < k; i++, m++)//之后放心的将s2的字符串添加进来{(s1 + i) = (s2+m);}for (i = n + k, m = 0; i < j + k; i++, m++)//最后完成添加的s1的最尾部再将之前传递给s3的字符赋值过来。{(s1+i) = (s3+m);}(s1 + k + j) = ’ ‘;//空格结束字符串}}
这里要把所有的字符串都看成数组来做就很方便了,这里说一下,假如s1是一个数组,那么s1就代表首元素的地址,s1就是首元素的地址所指向值,(s1+1)代表下一个元素的值。
四、编写函数insert(s1,s2,pos),实现在字符串s1中的指定位置po…
这是你2113多写了一句putchar(pos)造成的5261。把它去了就行。4102还有,怎么插入到1653pos位置,常规理解内是插入到此字符之间容啊?#include #include void insert(char *p1,char p2,char pos){int m,n,i;char temp[40];m=strlen(p1);n=strlen(p2);for(i=0;i;i++){if(pos==(p1+i)){strcpy(temp,p1+i);*(p1+i)=’\0’;strcat(p1,p2);strcat(p1,temp); puts(p1);break;}}}void main(){char s1[20], s2[20];char pos;printf(“Please input s1:”);gets(s1);printf(“Please input s2:”);gets(s2);printf(“Please input pos:”);pos=getchar();insert(s1,s2,pos);}