问题
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;
}
回答1:
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()
Here can replace gets()
using fgets()
by :-
fgets(st,50,stdin);
Modified code :-
#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;
}
Recommended :- move puts()
outside for-loop
.
Output :-
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
回答2:
" " is a space. I don't think this is your intended behavior. Use another buffer to make a copy. For example,
#include<stdio.h>
#include<string.h>
int main()
{
char sta[50];
char stb[50];
int i,j;
printf("ENter the string:\n");
gets(sta);
for(i=0,j=0;i<strlen(sta);i++)
{
switch(st[sta])
{
case '!':
case '"':
case '#':
case '$':
case '%':
case '&': break;
default:
stb[j++]=sta[i];
break;
}
stb[j] = (char)0; // C str termination...
printf("String is:\n");
puts(stb);
}
return 0;
}
回答3:
The following proposed code:
- cleanly compiles
- eliminates the 'magic' numbers
- properly replaces the listed punctuation marks with a space
- only prints the result once
- uses the 'valid' function
fgets()
rather than the (currently) nonexistentgets()
function - avoid comparing signed and unsigned values
- limits the scope of the variable
i
and now, the proposed code:
#include<stdio.h>
#include<string.h>
#define MAX_STR_LEN 50
int main( void )
{
char st[ MAX_STR_LEN + 1 ];
printf("ENter the string, max 50 characters\n");
fgets( st, sizeof( st ), stdin );
for( size_t i=0;i<strlen(st);i++)
{
switch(st[i])
{
case '!':
case '"':
case '#':
case '$':
case '%':
case '&':
st[i] = ' ';
break;
default:
break;
}
}
printf( "Modified String is:\n %s\n", st );
return 0;
}
来源:https://stackoverflow.com/questions/51600333/removing-punctuations-in-a-string-in-c-using-switch-case