读书人

字符替换有关问题 用了指针

发布时间: 2012-03-27 13:44:24 作者: rapoo

字符替换问题 用了指针,求解释
#include <stdio.h>
#define MAX 50

rep(char *s,char *s1,char *s2)
{
char *p;
for(;*s;s++)
{
for(p=s1;*p&&*p!=*s;p++);
if(*p) *s=*(p-s1+s2);
}
}
main()
{
char s[MAX];
char s1[MAX],s2[MAX];
clrscr();
puts("Please input the string for s:");
scanf("%s",s);
puts("Please input the string for s1:");
scanf("%s",s1);
puts("Please input the string for s2:");
scanf("%s",s2);
rep(s,s1,s2);
puts("The string of s after displace is:");
printf("%s\n",s);
puts("\n Press any key to quit ...");
getch();
}
在此处
for(p=s1;*p&&*p!=*s;p++);
if(*p) *s=*(p-s1+s2);
for循环后的分号做什么?那个 *s=*(p-s1+s2)怎样起的替换作用?

[解决办法]

C/C++ code
  1 #include <stdio.h>  2 #define MAX 50  3   4 rep(char *s,char *s1,char *s2)  5 {  6     char *p;  7   8     for(;*s;s++)  9      { 10         for(p=s1;*p&&*p!=*s;p++); 11         if(*p) 12           *s=*(p-s1+s2); 13      } 14 } 15 main() 16 { 17     char s[MAX]; 18     char s1[MAX],s2[MAX]; 19  20     clrscr(); 21     puts("Please input the string for s:"); 22     scanf("%s",s); 23     puts("Please input the string for s1:"); 24     scanf("%s",s1); 25     puts("Please input the string for s2:"); 26     scanf("%s",s2); 27     rep(s,s1,s2); 28     puts("The string of s after displace is:"); 29     printf("%s\n",s); 30     puts("\n Press any key to quit ..."); 31     getch(); 32 }
[解决办法]
C/C++ code
  1 #include <stdio.h>  2 #define MAX 50  3   4 rep(char *s,char *s1,char *s2)  5 {  6     char *p;  7   8     for(;*s;s++)  9      { 10         for(p=s1;*p&&*p!=*s;p++);//分号的作用是让p指向的字符和s所指向的字符相等 或 p指向NULL 11         if(*p) 12           *s=*(p-s1+s2); p-s1的值是p相对与s1的偏移量  你可以理解为s1[p-s1]==*p p-s1+s2同理 13      } 14 } 15 main() 16 { 17     char s[MAX]; 18     char s1[MAX],s2[MAX]; 19  20     clrscr(); 21     puts("Please input the string for s:"); 22     scanf("%s",s); 23     puts("Please input the string for s1:"); 24     scanf("%s",s1); 25     puts("Please input the string for s2:"); 26     scanf("%s",s2); 27     rep(s,s1,s2); 28     puts("The string of s after displace is:"); 29     printf("%s\n",s); 30     puts("\n Press any key to quit ..."); 31     getch(); 32 } 

读书人网 >C语言

热点推荐