Menu Close

C语言 – 指针和字符串

字符串是char数组,以空字符’\ 0’结尾。 我们可以使用指针来操作字符串。 这是解释此部分的示例:

例1.指针和字符串

#include <stdio.h>
#include <string.h>
int main()
{
    char str[]="Hello ZhiHuiXinPian";
    char *p;
    p=str;
    printf("First character is:%c\n",*p);
    p =p+1;
    printf("Next character is:%c\n",*p);
    printf("Printing all the characters in a string\n");
    p=str;  //reset the pointer
    for(int i=0;i<strlen(str);i++)
    {
       printf("%c\n",*p);
       p++;
    }
   return 0;
}

结果

例2.指针数组处理字符串

 #include <stdio.h>
int main()
{
   char *materials[ ] = { "iron",  "copper",  "gold"};
   printf("Please remember these materials :\n");
   int i ;
   for (i = 0; i < 3; i++) {
   printf("%s\n", materials[ i ]);}
   return 0;
}  

结果

 

除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in C语言教程

Related Posts