C语言笔记——字符串和文本02

C语言没有提供字符串数据类型,这与其他编程语言不同。
C语言使用char类型的数组元素存储字符串

1.1字符串定义

放在” “中的任何内容都被编译器视为字符串

C语言笔记——字符串和文本02_第1张图片

结果
This is on
two lines!

注意:C语言中字符串总是由\0字符结尾,所以字符串长度永远比字符串中的字符多1

1.2处理字符串和文本的方法

char saying[20];  
//声明字符串的数组,其大小至少要比所存储的字符是多1,因为编译器会自动在字符串常量的末尾添加\0
char saying[] = "This is a string.";
//或者直接初始化,不用指定大小

1.3字符串操作

1.3.1连接两个字符串

要对字符串执行算术赋值操作,必须逐个元素地赋值

//连接两个字符串
#include 

int main(void)
{
  char str1[40] = "To be or not to be";
  char str2[] = ",that is the question";
  int count1 = 0;                /* Length of str1 */
  int count2 = 0;                /* Length of str2 */

  /* find the length of the first string */
  while (str1[count1])          /* Increment count till we reach the string */
    count1++;                   /* terminating character.                 */

  /* Find the length of the second string */
  while (str2[count2])          /* Count characters in second string      */
    count2++;

  /* Check that we have enough space for both strings  */
  if(sizeof str1 < count1 + count2 + 1)
    printf("\nYou can't put a quart into a pint pot.");
  else
  {  /* Copy 2nd string to end of the first  */

     count2 = 0;                 /* Reset index for str2 to 0   */
    while(str2[count2])          /* Copy up to null from str2   */
      str1[count1++] = str2[count2++];

    str1[count1] = '\0';         /* Make sure we add terminator */
    printf("\n%s\n", str1 );     /* Output combined string      */

  }
  return 0;

连接两个字符,strcat

#include 
#include 
#define STR_LENGTH 40

int main(void)
{
  char str1[STR_LENGTH] = "To be or not to be";
  char str2[STR_LENGTH] = ",that is the question";

  if(STR_LENGTH > strlen(str1) + strlen(str2)) /* Enough space ?             */
    printf("\n%s\n", strcat(str1, str2));   /* yes, so display joined string */
  else
    printf("\nYou can't put a quart into a pint pot.");
  return 0;
}

1.3.2比较字符串strcmp

/* Comparing strings */
#include 
#include 

int main(void)
{
  char word1[20];                /* Stores the first word  */
  char word2[20];                /* Stores the second word */

  printf("\nType in the first word:\n 1: ");
  scanf("%19s", word1);            /* Read the first word    */
  printf("Type in the second word:\n 2: ");
  scanf("%19s", word2);           /* Read the second word   */

  /* Compare the two words */
  if(strcmp(word1,word2) == 0)
    printf("You have entered identical words");
  else
    printf("%s precedes %s",
                    (strcmp(word1, word2) < 0) ? word1 : word2,
                    (strcmp(word1, word2) < 0) ? word2 : word1);
  return 0;
}

1.3.3字符串中寻找字符或字符串

/*  找字符串中的某个字符串  */
#include 
#include 
int main(void)
{
  char str1[] = "This string contains the holy grail.";
  char str2[] = "the holy grail";
  char str3[] = "the holy grill";

  /* Search str1 for the occurrence of str2 */
  if(strstr(str1, str2) == NULL)
    printf("\n\"%s\" was not found.", str2);
  else
    printf("\n\"%s\" was found in \"%s\"",str2, str1);

  /* Search str1 for the occurrence of str3 */
  if(strstr(str1, str3) == NULL)
    printf("\n\"%s\" was not found.", str3);
  else
    printf("\nWe shouldn't get to here!");
  return 0;
}

1.4分析和转换字符串

如果需要检查字符串内部的内容,可以在头文件

/* 测试输入字符串中有多少个数字和字母 */
#include 
#include 

int main(void)
{
  char buffer[80];               /* Input buffer               */
  int i = 0;                     /* Buffer index               */
  int num_letters = 0;           /* Number of letters in input */
  int num_digits = 0;            /* Number of digits in input  */

  printf("\nEnter an interesting string of less than 80 characters:\n");
  gets(buffer);                  /* Read a string into buffer  */


  while(buffer[i] != '\0')
  {
    if(isalpha(buffer[i]))
      num_letters++;             /* Increment letter count     */
    if(isdigit(buffer[i++]))
      num_digits++;              /* Increment digit count      */
  }
  printf("\nYour string contained %d letters and %d digits.\n",
                                              num_letters, num_digits);
  return 0;
}

转换字符
使用函数toupper()和函数strstr()可以确定一个字符串中是否出现在哎另一个字符串中(忽略大小写)

#include 
#include <string.h>
#include 

int main(void)
{
  char text[100];                /* Input buffer for string to be searched */
  char substring[40];            /* Input buffer for string sought         */

  printf("\nEnter the string to be searched(less than 100 characters):\n");
  fgets(text, sizeof(text), stdin);

  printf("\nEnter the string sought (less than 40 characters ):\n");
  fgets(substring, sizeof(substring), stdin);

  /* overwrite the newline character in each string */
  text[strlen(text)-1] = '\0';
  substring[strlen(substring)-1] = '\0';

  printf("\nFirst string entered:\n%s\n", text);
  printf("\nSecond string entered:\n%s\n", substring);

  /* Convert both strings to uppercase. */
  for(int i = 0 ; (text[i] = toupper(text[i])) ; i++);
  for(int i = 0 ; (substring[i] = toupper(substring[i])) ; i++);

   printf("\nThe second string %s found in the first.",
              ((strstr(text, substring) == NULL) ? "was not" : "was"));
  return 0;
}

6.4.2将字符串转换成数值

在头文件

char value_str[] = "98.4";
double value = 0;
value = atof(valuestr);//将string转换成浮点数

将数字转换成字符

char *itoa( int value, char *string,int radix);[1] 原型说明: value:欲转换的数据。 string:目标字符串的地址。 radix:转换后的进制数,可以是10进制、16进制等。 C语言提供了几个标准库函数,可以将任意类型(整型、长整型、浮点型等)的数字转换为字符串。以下是用itoa()函数将整数转换为字符串的一个例子:

 # include  
 # include  
{      
    int num = 100;     
    char str[25];  
    itoa(num, str, 10); 
    printf("The number 'num' is %d and the string 'str' is %s. \n" ,                        num, str); }

你可能感兴趣的:(c,c语言)