使用Switch大小写删除C中字符串中的标点符号 [英] Removing Punctuations in a string in C using Switch case
本文介绍了使用Switch大小写删除C中字符串中的标点符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以帮助我,告诉我代码有什么问题吗?我使用开关盒制作了解决方案,并将标点符号替换为空字符串.
Can someone please help me and tell what is wrong with my code. I made the solution using switch case and replace the punctuations with empty string.
#include<stdio.h>
#include<string.h>
int main()
{
char st[50];
int i;
printf("ENter the string:\n");
gets(st);
for(i=0;i<strlen(st);i++)
{
switch(st[i])
{
case '!':
case '"':
case '#':
case '$':
case '%':
case '&':strcpy(st[i]," ");
break;
}
printf("String is:\n");
puts(st);
}
return 0;
}
推荐答案
-
strcpy(st[i]," ")
错误使用st[i]=' '
; (strcpy用于复制字符串,是单个字符直接分配的情况下的过程).
现在从 -
gets(st)
,它导致了buffer overflows
.使用fgets()
. 详细了解gets()和fgets()
C
中删除了strcpy(st[i]," ")
is wrong usest[i]=' '
; (strcpy is for copy strings , is case of single char direct assignment is the process ) .gets(st)
is now removed fromC
.It causesbuffer overflows
. Usefgets()
. Read more on gets() and fgets()
这里可以使用fgets()
将gets()
替换为:-
Here can replace gets()
using fgets()
by :-
fgets(st,50,stdin);
修改后的代码:-
#include <stdio.h>
#include <string.h>
int main()
{
char st[50];
int i;
printf("ENter the string:\n");
fgets(st, 50, stdin);
for (i = 0; i < strlen(st); i++)
{
switch (st[i])
{
case '!':
case '"':
case '#':
case '$':
case '%':
case '&':
st[i] = ' ';
break;
}
printf("String is:\n");
puts(st);
}
return 0;
}
推荐:-将puts()
移到for-loop
之外.
Recommended :- move puts()
outside for-loop
.
输出:-
ENter the string:
!hello#%worl$
String is:
hello#%worl$
String is:
hello#%worl$
String is:
hello#%worl$
String is:
hello#%worl$
String is:
hello#%worl$
String is:
hello#%worl$
String is:
hello %worl$
String is:
hello worl$
String is:
hello worl$
String is:
hello worl$
String is:
hello worl$
String is:
hello worl$
String is:
hello worl
String is:
hello worl
这篇关于使用Switch大小写删除C中字符串中的标点符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文