- 以单词为单位,进行逆置(建议指针)
“hello 22111 student” ===> “student 22111 hello”
#include <stdio.h>
#include <string.h>
void fun();
int main(int argc, const char *argv[])
{
int i,j;
char str[64]="hello 124 world";
char *p=str;
i=0;j=strlen(str)-1;
fun(str,i,j);
i=0;j=0;
printf("调转%s\n",str);
while(*p!='\0')
{
while(*p!=' '&&*p!='\0')
{
p=p+1;
j++;
}
j--;
fun(str,i,j);
j=j+1;
while(*p==' ')
{
p=p+1;
j++;
}
i=j;
}
printf("逆值%s\n",str);
return 0;
}
void fun(char str[64],int i,int j)
{
char temp;
while(i<j){
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;j--;
}
}
2,使用指针实现字符串逆置
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
char str[50];
char temp;
printf("请输入字符串");
gets(str);
char *p=str;
int i=0,j=strlen(str)-1;
while(i<j)
{
temp=*(p+i);
*(p+i)=*(p+j);
*(p+j)=temp;
i++;j--;
}
printf("逆置为%s\n",str);
return 0;
}
3,使用指针计算计算每一位数字的和
“fa4621” ===>4+6+2+1=13
#include <stdio.h>
int main(int argc, const char *argv[])
{
printf("请输入");
char str[50];
scanf("%s",str);
char *p=str;
int sum=0;
while(*p!='\0')
{
if(*p>='0'&&*p<='9'){
sum=sum+*p-48;
}
p++;
}
printf("字符和为%d\n",sum);
return 0;
}
4,分析以下指针
Int a=100; int *p=&a;
*p++ 值为100,指针指向下一个int长度的地址;
*++p 指针指向下一个int长度的地址,然后取值;
*(p+2) 指针指向后面的2个int长度的地址,然后取值;
*p-2 指针p取值,然后减2
&p+1 对指针p取地址,然后加1;
--*p 对p取值,然后减1;
&a+1 对a取地址,然后加一个int的长度
&a-- 报错。