美文网首页
9. 字符串 Charater Strings

9. 字符串 Charater Strings

作者: 53df91bc24df | 来源:发表于2016-08-16 08:32 被阅读39次

    9.1 基础

    字符串,由一维字符数组组成(字符型)。 1 代表文本。2 验证用户输入。3 创建格式化字符串。用双引号包含。"This is a string", "Hello World", "xyz 123 *!#@&"都是字符串。

    存储:在C中,存储成由一个指定的字符串末端的名为NULL的符号敞亮种植的字符型数组。NULL常量的数值是'\0'(转义序列符)。双引号不被存储为string的一部分。可以利用下标、指针符对string(数组)进行处理,NULL字符能用来监测string末端。

    i/o

    #include <stdio.h>
    getchar()putchar()提供single字符的io。
    gets()puts()由上面两个函数编写而来,能按完整单元处理字符串。

    #include <stdio.h>
    #define MSIZE 81//够80个字符+'\0'(合计81个)使用。
    
    int main()
    {
    
        char message[MSIZE]; 
        
        printf("Enter a string:\n");
        gets(message);
        printf("The string just entered is:\n");
        puts(message);
        //printf("s%\n", message)
        
        return 0;
    }
    

    1 按Enter,产生一个\n,gets()解释这个字符为输入末端。除了\n,所有的输入都被存储在了message数组中
    2 printf()能代替puts(),但scanf()不能代替gets()

    processing

    1 strcopy()把string2内容复制到string1
    当string2[i]不等于'\0'时,循环,string1[i] = string2[i]。
    *但需确保string1有足够的长度保存string2。

    #include <stdio.h>
    
    void strcopy(char [], char []); /* expects two arrays of chars */
    
    int main()
    {
    #define LSIZE 81
        char message[LSIZE];  /* enough storage for 80 characters plus '\0' */
        char newMessage[LSIZE]; /* enough storage for a copy of message */
        
        printf("Enter a sentence: ");
        gets(message);
        
        strcopy(newMessage, message); /* pass two array addresses */
        
        puts(newMessage);
        
        return 0;
    }
    
    /* copy string2 to string 1 */
    void strcopy (char string1[], char string2[]) /* two arrays are passed */
    {
        int i = 0;  /* i will be used as a subscript */
        
        while (string2[i] != '\0') /* check for the end-of-string *///检测字符串末端
        {
            string1[i] = string2[i]; /* copy the element to string1 */
            i++;
        }
        string1[i] = '\0'; /* terminate the copied string */
    }
    

    把赋值语句包含在while语句的测试部分内

    #include <stdio.h>
    int main()
    {
    #define LSIZE 81
        char message[LSIZE];  /* enough storage for 80 characters plus '\0' */
        char c;
        int i;
        
        printf("Enter a string:\n");
    ////////
        i = 0;
        while(i < (LSIZE-1) && (c = getchar()) != '\n')
        {
            message[i] = c; /* store the character entered */
            i++;
        }
        message[i] = '\0'; /* terminate the string */
    ////////取代了上个代码中的gets()函数。构成一个从一个终端输入一正航字符的独立单元,因此这些语句能从main()函数移走。
        printf("The string just entered is: \n");
        puts(message);
        
        return 0;
    }
    

    9.2 库函数

    C标准库中,有大量字符串处理函数和字符处理函数。

    字符串库函数(string.h)

    名称 描述
    strcpy(str1, str2) 复制str2到str1,包括'\0'
    strcat(str1, str2) 附加str2到str1的末端
    strlen(sting) 返回string的长度,不包括'\0'
    strccmp(str1, str2) 比str2 str1长,1<2返回-1,==返回0,>返回正整数
    strncpy(str1, str2, n) str2的n字符复制到str1,若str2<n,用'\0'补
    strncmp(str1, str2, n) 比str1 str2最多n个字符
    strchr(string, char) char在string中第一次出现的位置,返回这个字符地址

    "Behop"大于"Beehive",因为h>e
    字母排在后面的大,小写字母>大写字母

    #include  <stdio.h>
    #include <string.h> /* required for the string function library */
    
    int main()
    {
    #define MAXELS 50
        char string1[MAXELS] = "Hello";
        char string2[MAXELS] = "Hello there";
        int n;
        
        n = strcmp(string1, string2);
        
        if (n < 0)
            printf("%s is less than %s\n\n", string1, string2);
        else if (n == 0)
            printf("%s is equal to %s\n\n", string1, string2);
        else
            printf("%s is greater than %s\n\n", string1, string2);
        
        printf("The length of string1 is %d characters\n", strlen(string1));
        printf("The length of string2 is %d characters\n\n", strlen(string2));
        
        strcat(string1," there World!");
        
        printf("After concatenation, string1 contains the string value\n");
        printf("%s\n", string1);
        printf("The length of this string is %d characters\n\n",
               strlen(string1));
        
        printf("Type in a sequence of characters for string2:\n");
        gets(string2);
        
        strcpy(string1, string2);
        
        printf("After copying string2 to string1");
        printf(" the string value in string1 is:\n");
        printf("%s\n", string1);
        printf("The length of this string is %d characters\n\n",
               strlen(string1));
        printf("\nThe starting address of the string1 string is: %d\n",
               (void *) string1);
        return 0;
    }
    

    字符函数

    ctype.h

    原型 描述
    int isalpha(char) 是字母返!0,or 0
    int isupper(char) 是大写返!0,or 0
    int islower(char) 是小写返!0,or 0
    int isdigit(char) 是0-9返!0,or 0
    int isascii(char) 是ASCII返!0,or 0
    int isspace(char) 是空格返!0,or 0
    int isprint(char) 是能打印返!0,or 0
    int iscntrl(char) 是控制字符返!0,or 0
    int ispunct(char) 是标点字符返!0,or 0
    int toupper(char) 是小写,则返回相应大写,or 不变
    int tolower(char) 是大写,则返回相应小写,or 不变
    #include <stdio.h>
    #include <ctype.h> /* required for the character function library */
    
    int main()
    {
    #define MAXCHARS 100
        char message[MAXCHARS];
        void convertToUpper(char []);  /* function  prototype */
        
        printf("\nType in any sequence of characters:\n");
        gets(message);
        
        convertToUpper(message);
        
        printf("The characters just entered, in uppercase are:\n%s\n", message);
        
        return 0;
    }
    
    // this function converts all lowercase characters to uppercase
    void convertToUpper(char message[])
    {
        int i;
        for(i = 0; message[i] != '\0'; i++)
            message[i] = toupper(message[i]);
    }
    

    转换函数

    stdlib.h

    原型 描述
    int atoi(string) 转换ASCII字符串为整数,在第一个非整数字符处停止转换
    double atof(string) 转换ASCII字符串为双精数值,在第一个不能被解释为双精的字符处停止转换
    char[] itoa(string) 转换一个整数为ASCII字符串。分配足够空间。

    atoi和atof的使用

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h> // required for test conversion function library
    #define MAXELS 20
    
    int main()
    {
      char test[MAXELS] = "1234";
      int num;
      double dnum;
    
      num = atoi(test);
      printf("The string %s as an integer number is %d\n", test,num);
      printf("This number divided by 3 is: %d\n", num/3);
      
      strcat(test, ".96");
    
      dnum = atof(test);
      printf("\nThe string %s as a double number is: %f\n", test,dnum);
      printf("This number divided by 3 is: %f\n", dnum/3);
      
      return 0;
    }
    

    9.3 输入数据验证

    验证输入的是否为整数
    1

    #include <stdio.h>
    #include <stdlib.h>  /* needed to convert a string to an integer */
    #define MAXCHARS 40
    #define TRUE 1
    #define FALSE 0
    
    int isvalidInt(char []);  /* function prototype */
    
    int main()
    {
        
        char value[MAXCHARS];
        int number;
        
        printf("Enter an integer: ");
        gets(value);
        
        if (isvalidInt(value)== TRUE)
        {
            number = atoi(value);
            printf("The number you entered is %d\n", number);
        }
        else
            printf("The number you entered is not a valid integer.\n");
        
        return 0;
    }
    
    int isvalidInt(char val[])
    {
        int start = 0;
        int i;
        int valid = TRUE;
        int sign = FALSE;
        
        /* check for an empty string */
        if (val[0] == '\0') valid = FALSE;
        
        /* check for a leading sign */
        if (val[0] == '-' || val[0] == '+')
        {
            sign = TRUE;
            start = 1;  /* start checking for digits after the sign */
        }
        
        /* check that there is at least one character after the sign */
        if(sign == TRUE && val[1] == '\0') valid = FALSE;
        
        /*now check the string, which we know has at least one non-sign char */
        i = start;
        while(valid == TRUE && val[i] != '\0')
        {
            if (val[i] < '0' || val[i] > '9') /* check for a non-digit */
                valid = FALSE;    
            i++;
        }
        
        return valid;
    }
    

    优化

    #include <stdio.h>
    #include <stdlib.h>
    
    int getanInt();  /* function prototype */
    
    int main()
    {  
      int value;
    
      printf("Enter an integer value: ");
      value = getanInt();
      printf("The integer entered is: %d\n", value);
    
      return 0;
    }
    
    #define TRUE 1
    #define FALSE 0
    #define MAXCHARS 40
    int getanInt()
    {
      int isvalidInt(char []);  /* function prototype */
    
      int isanInt = FALSE;
      char value[MAXCHARS];
    
      do
      {
        gets(value);
        if (isvalidInt(value) == FALSE)
        {
          printf("Invalid integer - Please re-enter: ");
          continue; /* send control to the do-while expression test */
        }
        isanInt = TRUE;
      }while (isanInt == FALSE);
    
      return (atoi(value));  /* convert to an integer */
    }
    
    int isvalidInt(char val[])
    {
      int start = 0;
      int i;
      int valid = TRUE;
      int sign = FALSE;
    
      /* check for an empty string */
      if (val[0] == '\0') valid = FALSE;
    
      /* check for a leading sign */
      if (val[0] == '-' || val[0] == '+')
      {
        sign = TRUE;
        start = 1;  /* start checking for digits after the sign */
      }
    
      /* check that there is at least one character after the sign */
      if(sign == TRUE && val[1] == '\0') valid = FALSE;
    
      /*now check the string, which we know has at least one non-sign char */
      i = start;
      while(valid == TRUE && val[i] != '\0')
      {
        if (val[i] < '0' || val[i] > '9') /* check for a non-digit */
            valid = FALSE;    
        i++;
      }
    
       return valid;
    }
    

    *9.4 格式化字符串

    print("|% 数字s|")
    

    正数,右对齐
    负数,左对齐

    9.5 字符和单词计数

    字符计数

    #include <stdio.h>
    #define MAXNUM 1000
    
    int countchar(char []);  /* function prototype */
    
    int main()
    {
        char message[MAXNUM];
        int numchar;
        
        printf("\nType in any number of characters: ");
        gets(message);
        numchar = countchar(message);
        printf("The number of characters just entered is %d\n", numchar);
        
        return 0;
    }
    
    int countchar(char list[])
    {
        int i, count = 0;
        
        for(i = 0; list[i] != '\0'; i++)
            count++;
        
        return(count);
    }
    

    单词计数

    #include <stdio.h>
    #define MAXNUM 1000 
    
    int countword(char []);  /* function prototype */
    
    int main()
    {
      char message[MAXNUM];
      int numchar;
      
      printf("\nType in any number of words: ");
      gets(message);
      numchar = countword(message);
      printf("The number of words just entered is %d\n", numchar);
    
      return 0;
    }
    
    int countword(char list[])
    #define YES 1
    #define NO 0
    {
      int i, inaword, count = 0;
    
      inaword = NO;
      for(i = 0; list[i] != '\0'; i++)
      {
        if (list[i] == ' ')
          inaword = NO;
        else if (inaword == NO)
        {
          inaword = YES;
          count++;
        }
      }
    
      return(count);
    }
    

    相关文章

      网友评论

          本文标题:9. 字符串 Charater Strings

          本文链接:https://www.haomeiwen.com/subject/sljusttx.html