HeadFirstC笔记_2.5 字符串:字符串原理

所谓的字符串数组,其实就是个二维的字符数组
   
    
    
  1. char tracks[][80] = {
  2. "I left my heart in Harvard Med School",
  3. "Newark, Newark - a wonderful town",
  4. "Dancing with a Dork",
  5. "From here to maternity",
  6. "The girl from Iwo Jima",
  7. };
  8. // []-->第一对方括号用来访问由所有字符串组成的数组,编译器可以识别你有5个字符串,因此括号里可以不写数字。
  9. // [80]-->第二对方括号用来访问每个单独的字符串,歌名不得超过79个字符,所以将这个值设为80
为了找到某一首歌的名字,可以这样写:
    
     
     
  1. tracks[4] --> "The girl from Iwo Jima"
如果想读取字符串中的某个字符,可以这样写:
     
      
      
  1. tracks[4][6] --> 'r' // 这是第5个字符串中第7个字符

使用string.h头文件
c标准库中处理字符串的代码都包含在string.h这个头文件中,你只需把string.h加在程序的顶端,
就像你包含stdio.h那样,就可以调用里面的函数了。
      
       
       
  1. #include <stdio.h> // 主要处理输入输出
  2. #include <string.h> // 主要处理字符串

主要函数:
strchr() 在字符串中查找字符
strcmp() 比较字符串
strstr() 在字符串中查找字符串
strcpy() 复制字符串
strlen() 返回字符串的长度
strcat() 连接字符串
注:如果你用的是Mac或Linux的计算机,可以在命令行中查看string.h中每个函数的详细介绍,
比如你想查看strstr()函数,可以输入:man strstr

使用strstr()函数
       
        
        
  1. // 函数会在第一个字符串里寻找第二个字符串,
  2. // 如果找到会返回第二个字符串在存储器中的位置
  3. // 如果没找到则返回0
  4. strstr("dysfunctional", "fun");

代码示例:
        
         
         
  1. #include <stdio.h>
  2. #include <string.h>
  3. //把tracks数组放在全局域。全局变量位于任何函数之外,所有函数都可以调用它们。
  4. char tracks[][80] = {
  5. "I left my heart in Harvard Med School",
  6. "Newark, Newark - a wonderful town",
  7. "Dancing with a Dork",
  8. "From here to maternity",
  9. "The girl from Iwo Jima"
  10. };
  11. // find_track()必须赶在你在main()中调用它之前出现,否则会警告冲突
  12. // 从tracks字符串数组中找到输入的字符串所在的那个字符串
  13. void find_track(char search_for[]){
  14. int i;
  15. for(i = 0; i<5;i++){
  16. if(strstr(tracks[i],search_for)){
  17. printf("Track %i: '%s'\n",i,tracks[i]);
  18. }
  19. }
  20. }
  21. int main(){
  22. char search_for[80];
  23. printf("search_for:");
  24. fgets(search_for,sizeof(search_for),stdin);
  25. search_for[strlen(search_for)-1] = '\0';
  26. find_track(search_for);
  27. return 0;
  28. }
运行结果:
 

反转字符串
        
         
         
  1. #include <stdio.h>
  2. #include <string.h>
  3. //反转字符串
  4. void print_reverse(char *s) {
  5. // 先计算出字符串的长度,size_t相当于整型,用来保存字符串的长度
  6. size_t len = strlen(s);
  7. // 先把指针移到字符数组最后一位
  8. char *t = s+len-1 ;
  9. // 然后再依次反向移动
  10. while( t >= s) {
  11. printf("%c",*t);
  12. t = t-1; //像这样计算地址就叫 指针算术运算
  13. }
  14. puts("");
  15. }
  16. int main() {
  17. char search_for[80];
  18. printf("search_for:");
  19. fgets(search_for,sizeof(search_for),stdin);
  20. search_for[strlen(search_for)-1] = '\0';
  21. print_reverse(search_for);
  22. return 0;
  23. }
运行结果:
 

字符串数组还可以写成字符指针的数组的形式
         
          
          
  1. char *names_for_dog[] = { "Bowser", "Bonza", "Snodgrass"};
  2. char *a = names_for_dog[0];
  3. char *b = names_for_dog[1];
  4. char *c = names_for_dog[2];

猜你喜欢

转载自blog.csdn.net/woshiwangbiao/article/details/53486442