C語言:在字符串中刪除與某字符相同的字符


用字符指針作函數參數編程實現如下功能:在字符串中刪除與某字符相同的字符。 **輸入格式要求:"%s" 輸入提示信息: "Input a string:" "Input a character:" **輸出格式要求:"Results:%s\n" 程序運行示例1如下: Input a string:hello,world! Input a character:o Results:hell,wrld!
 1 #include <stdio.h>
 2 #include <string.h>
 3 #define N 100
 4 void  Squeeze(char *s, char c);
 5 int main()
 6 {
 7     char  str[20], ch;
 8     printf("Input a string:");
 9     gets(str);
10     printf("Input a character:");
11     ch = getchar();
12     Squeeze(str,ch);
13     printf("Results:%s\n", str);
14     return 0;
15 }
16 void  Squeeze(char *s, char c)
17 {
18     int i,j,len;
19     len = strlen(s);
20     for (i = len; i>=0; i--)
21     {
22         if (s[i] == c)
23         {
24             for (j = i; j < len; j++)
25             {
26                 s[j] = s[j + 1];
27             }
28         }
29     }
30 }
做法一
 
        
 1 #include <stdio.h>
 2 #include <string.h>
 3 #define N 100
 4 void  Squeeze(char *s, char c);
 5 int main()
 6 {                      
 7     char  str[20], ch;
 8     printf("Input a string:");
 9     gets(str);
10     printf("Input a character:");
11     ch = getchar();
12     Squeeze(str, ch);
13     printf("Results:%s\n", str);
14     return 0;
15 }                      
16 void  Squeeze(char *s, char c)
17 {                      
18     char str[N];
19     char *t = str;
20     strcpy(t, s);
21     for (; *t != '\0'; t++)
22     {                      
23         if (*t != c)
24         {                      
25             *s = *t;
26             s++;
27         }
28     }
29     *s = '\0';  /* 在字符串t2的末尾添加字符串結束標志 */
30 }          
做法二

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM