c语言 字符串 string.h

C语言字符串(windows)

字符串的定义

 #include 
 ​
 int main(void) {
     
     //单个字符
     char c = 'c';
 ​
     //多个字符 串起来 String
     char arr[] = { "Hello" };   // 隐式定义
     //'H' 'e' 'l' 'l' 'o' '\0'
     /*
     错误示范
     char str[5] = "Hello";
     
     printf("%c", str);
     
     输出结果为 烫烫烫
     */
     //字符串如果不用于修改定义成const char arr[] = "Hello";
     
     //char* ptr = "Hello";  ptr指向H 指针形式定义的字符串不可修改  
     const char* ptr = "Hello"; //这样定义以免对字符串进行修改而报错
     //修改字符串的的字母(元素)
     arr[0] = 'q';
     
     printf("%s", arr);
 ​
     return 0;
 }

strcpy_s用法

string copy:复制字符串

 #include 
 #include 
 int main(void) {
 ​
     const char src[] = "Hello";
 ​
     char dest[50];
 ​
     //strcpy(dest ,src);    早期函数,有安全问题
     strcpy_s(dest, 50, src); //50写成sizeof(dest)也行
     //strcpy_s(dest, 4, src);   缓冲区太小导致src不能copy到dest里 缓冲区溢出
     printf("%s", dest);
 ​
     return 0;
 }

VS编译器捕获字符串异常

 #include 
 #include 
 #include 
 #include 
 ​
 void my_invalid_parm_handler(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t p_reserved) {
     wprintf(L"Invalid parameter detected in function %s.File:%s Line %d\n", function, file, line);
     wprintf(L"Expression:s\n", expression);
 ​
 };
 ​
 int main(void) {
     _set_invalid_parameter_handler(my_invalid_parm_handler);
 ​
     const char src[] = "Hello";
 ​
     char dest[2];
 ​
     errno_t err = strcpy_s(dest, sizeof(dest), src);
 ​
     if (err != 0) {
         printf("Error copying string.Error code:%d\n, err");
     }
     else {
         printf("%s\n", dest);
     }
 ​
     printf("%s\n", dest);   //buffer is too small 捕获异常
 ​
 ​
     return 0;
 }

通过release可以捕获错误

strlen

string length:计算字符串长度(不计算'\0')

 #include 
 ​
 int main(void) {
     //strlen:string length
 ​
     char dest[50] = "Hello";
 ​
     printf("%zd", strlen(dest)); //不统计'\0'
     
 ​
     return 0;
 }

微软认为不安全 以下是消除警告的代码

 #include 
 #include 
 ​
 int main(void) {
     
     char dest[50] = {0};
 ​
     strcpy_s(dest, sizeof(dest), "Hello");
 ​
     printf("%zd\n", strlen(dest));
 ​
     return 0;
 }

strcat_s

string concatenate:拼接字符串

 #include 
 #include 
 ​
 int main(void) {
     
     char dest[50] = {0};
 ​
     strcpy_s(dest, 50, "Hello");
 ​
     const char* src = ", world!\n";
 ​
     //dest = "Hello, world!"
 ​
     rsize_t dest_size = sizeof(dest) - strlen(dest) - 1;    //dest剩下的位置 = dest能放下的位置 - 已经存进去的位置 - '\0'
 ​
     //strcat(dest, src); 原始函数,不安全
     strcat_s(dest, dest_size, src);
 ​
     printf("%s", dest);
 ​
     return 0;
 }

sprintf_s

string print:字符串格式化输出

 #include 
 #include 
 ​
 int main(void) {
     //sprintf() sprintf_s()
 ​
     //避免缓冲区溢出
 ​
     char buffer[50] = {0};
     int number = 3;
     double pi = 3.14159;
 ​
     int ret = sprintf_s(buffer, sizeof(buffer), "Integer:%d, Double:%.2f", number, pi);
 ​
     if (ret > 0) {
     
         printf("Formatted string:%s\n", buffer);
     
     }
     else {
     
         printf("Error formatting string!\n");
     
     }
     return 0;
 }

strncpy_s

复制指定数量的字符

 #include 
 #include 
 ​
 int main(void) {
     
     //strncpy strncpy_s
 ​
     char dest[20];
     const char* src = "Hello, world!\n";
 ​
     size_t max_cpy = 10; //最多复制10个字符
 ​
     errno_t result = strncpy_s(dest, sizeof(dest), src, max_cpy);
 ​
     if (result == 0) {
         printf("Copied string :%s\n", dest);
     }
     else {
         printf("Error copying string.");
     
     }
 ​
     return 0;
 }

strncat_s

拼接指定数量的字符

 #include 
 #include 
 ​
 int main(void) {
     // strncat_s 
     // 最多追加多少个字符
 ​
     char dest[20] = {0};
 ​
     strcpy_s(dest, sizeof(dest), "Hello");
 ​
     const char* src = ", world!\n";
 ​
     size_t max_append = 7; //最多追加7个字符
 ​
     errno_t result = strncat_s(dest, sizeof(dest), src, max_append);
 ​
     if (result == 0) {
         printf("Concatenated String:%s\n", dest);
     }
     else {
         printf("Error concatenating string\n");
     }
 ​
     return 0;
 }

puts & gets_s

puts

 #include 
 ​
 int main(void) {
 ​
     //puts();
 ​
     puts("hello");
 ​
     const char* str = "Hello";
 ​
     puts(str);  //专门输出字符串
 ​
     return 0;
 }

gets_s

 #include 
 ​
 int main(void) {
 ​
     // gets() 原始函数 ---- gets_s()
 ​
     char buffer[100];
 ​
     gets_s(buffer, sizeof(buffer));
     
     printf("You enter:%s\n", buffer);
     /*更加安全
     
     if (gets_s(buffer, sizeof(buffer)) != NULL)
     {
         printf("You enter:%s\n", buffer);
     }
     else
     {       
     printf("Error or end of the file");
     }
     */
 ​
     return 0;
 }

strtok_s

string tokenize:分解字符串

 #include 
 #include 
 int main(void) {
     // strtok()原始函数 ——————————————strtok_s
 ​
     // 按照要求分解字符串
 ​
     char str[] = "This is a sample string";
     char delim[] = " ";
     char* token;
     char* context = {0};    // 保存strtok_s函数在其内部位置之间的上下文指针
 ​
     token = strtok_s(str, delim, &context);
 ​
     while (token != NULL) {
         printf("Token:%s\n", token);
         token = strtok_s(NULL, delim, &context);
     }
 ​
 ​
     return 0;
 }

strcmp

string compare:比较字符

 #include 
 #include 
 int main(void) {
 // 但凡是涉及到字符串修改的都有函数都带有_s
 ​
     // strcmp;
     //strncmp;
 ​
     const char* str1 = "Hello, world!";
     const char* str2 = "Hello, world!";
     const char* str3 = "Hello, guys!";
 ​
     if (strcmp(str1, str2) == 0) {
         printf("Str1 and str2 are equal!\n");
     }
     else {
         printf("Str1 and str2 are not equal!\n");
     }
     if (strcmp(str1, str3) == 0) {
         printf("Str1 and str3 are equal!\n");
     }
     else {
         printf("Str1 and str3 are not equal!\n");
     }
 ​
     int value1 = strcmp(str1, str3);    // ASCII码 g < w str3 < str1
 ​
     printf("%d\n", value1);// > 0
 ​
     int value2 = strcmp(str3, str1);
 ​
     printf("%d\n", value2);// < 0
 ​
     return 0;
 }

strncmp

比较指定个数字符

 #include 
 #include 
 int main(void) {
 // 但凡是涉及到字符串修改的都有函数都带有_s
 ​
     // strcmp;
     //strncmp;
 ​
     const char* str1 = "Hello, world!";
     const char* str2 = "Hello, world!";
     const char* str3 = "Hello, guys!";
 ​
     size_t max_count = 8; // 比较前8个字符
 ​
     if (strncmp(str1, str2, max_count) == 0) {
         printf("Str1 and str2 are equal!\n");   //相同
     }
     else {
         printf("Str1 and str2 are not equal!\n");
     }
     if (strncmp(str1, str3, max_count) == 0) {
         printf("Str1 and str3 are equal!\n");
     }
     else {
         printf("Str1 and str3 are not equal!\n");   //不同
     }
 ​
     return 0;
 }

strchr & strrchr

string chararacter:寻找指定char(从第一个开始)

string reverse char:寻找指定char(从最后一个开始)

得到的char的位置都是从第一个字符开始数

 #include 
 #include 
 int main(void) {
     const char* str = "Hello, worwlwd!";
 ​
     //strchr()
     //strrchr()
 ​
     char to_find = 'w';
 ​
     char* ptr_char = strchr(str, to_find);
 ​
     char* ptr_reverse_char = strrchr(str, to_find);
 ​
     if (ptr_char) {
         printf("找到了,%c的位置是:%td\n", to_find, ptr_char - str + 1);    //w的位置 -"Hello, world!"首地址 + 数组下标与实际顺序的差值(1) ptrdiff_t
     }
     else {
         printf("没有找到");
     }
 ​
     if (ptr_reverse_char) {
         printf("找到了,从后面找%c的位置是%td\n", to_find, ptr_reverse_char - str+1);
     }
     else {
         printf("没有找到");
     }
 ​
     return 0;
 }

strstr

string string:在一个string中寻找另一个string

 #include 
 #include 
 int main(void) {
     //strstr
     const char* text = "This is a simple test simple string";   //母字符串
     const char* sub = "simple"; //子字符串 大小写敏感 注意长度不要溢出
         
     char* result = strstr(text, sub);   // 子字符串为" " result值是NULL
 ​
     if (result != NULL) {
         printf("Found %s in %s at position :%td\n", sub, text, result - text + 1);
     }
     else {
         printf("Substring %s not found in %s\n", sub, text);
     }
 ​
     return 0;
 }

strspn & strcspn

string span:字符串前面相同的字符数

 #include 
 #include 
 int main(void) {
     
     // strcspn()
     const char* str1 = "12345abcdefghi678910";
     const char* str2 = "12345678910";
 ​
     size_t len = strspn(str1, str2);
 ​
     printf("%zu\n", len);
 ​
     return 0;
 }

string compliment span:字符串相同字符之前不同的字符数

 #include 
 #include 
 int main(void) {
     
     // strcspn()
     const char* str1 = "abcdefg12345";
     const char* str2 = "12345678910";
 ​
     size_t len = strcspn(str1, str2);
 ​
     printf("%zu\n", len);
 ​
     return 0;
 }
 #include 
 #include 
 int main(void) {
     //验证字符串是否有非法字符
     char input[] = "filename.txt";
 ​
     char invalid_chars[] = "/\\:*?\"<>|";
 ​
     if (strcspn(input, invalid_chars) < strlen(input)) {
         printf("Input contains invalid characters\n");
     }
     else {
         printf("Input is valid\n");
     }
 ​
     return 0;
 }

本章练习

 #include 
 #include 
 #include 
 ​
 #define TEXT_SIZE 100
 #define WORD_SIZE 50
 #define DELIMS " ,.!?\n"
 ​
 void replaceWord(const char* text, const char* oldWord, const char* newWord, const char* result);
 int countChar(const char* text, char ch);
 int countWords(const char* text);
 void extractUniqueWords(const char* text, char uniqueWords[][WORD_SIZE], int* uniqueCount);
 ​
 int main(void) {
 ​
     char text[TEXT_SIZE] = "This is a simple test.This text is for testing";
 ​
     char replacedText[TEXT_SIZE] = { 0 };
 ​
     char oldWord[] = "test";
 ​
     char newWord[] = "example";
 ​
     char countCharTarget = 's';
 ​
     char uniqueWords[TEXT_SIZE][WORD_SIZE] = { 0 };
 ​
     int uniqueCount = 0;
     // 替换指定单词
     replaceWord(text, oldWord, newWord, replacedText);
     printf("Replaced Text:%s\n", replacedText);
     // 计算特定字母数量
     int charCount = countChar(replacedText, countCharTarget);
     printf("Char %c appears %d times\n", countCharTarget, charCount);
     // 计算特定单词数量
     int wordCount = countWords(replacedText);
     printf("Total number of words :%d\n", wordCount);
     // 提取特定单词
     extractUniqueWords(replacedText, uniqueWords, &uniqueCount);
     puts("Unique words:");
 ​
     for (int i = 0; i < uniqueCount; i++) {
         printf("%s\n", uniqueWords[i]);
 ​
     }
 ​
     return 0;
 }
 void replaceWord(const char* text, const char* oldWord, const char* newWord, const char* result) {
 ​
     char buffer[TEXT_SIZE] = { 0 };
     const char* pos = text;
     const char* temp = text;
     size_t oldLen = strlen(oldWord);
 ​
     while ((temp = strstr(pos, oldWord)) != NULL) {
         strncat_s(buffer, sizeof(buffer), pos, temp - pos);
         strcat_s(buffer, sizeof(buffer), newWord);
         pos = temp + oldLen;
 ​
     }
 ​
     strcat_s(buffer, sizeof(buffer), pos);
     strcpy_s(result, TEXT_SIZE, buffer);
 ​
 }
 int countChar(const char* text, char ch) {
     int count = 0;
     while (*text) {
         if (*text == ch) {
             count++;
         }
         text++;
     }
 ​
 ​
     return count;
 }
 int countWords(const char* text) {
     int count = 0;
     char buffer[TEXT_SIZE] = { 0 };
 ​
     strcpy_s(buffer, TEXT_SIZE, text);
 ​
     char* context = NULL;
 ​
     char token = strtok_s(buffer, DELIMS, &context);
 ​
     while (token != NULL) {
         count++;
         token = strtok_s(NULL, DELIMS, &context);
 ​
 ​
     }
     return count++;
 }
 void extractUniqueWords(const char* text, char uniqueWords[][WORD_SIZE], int* uniqueCount) {
     char tempText[TEXT_SIZE] = { 0 };
     strcpy_s(tempText, TEXT_SIZE, text);
 ​
     char* context = NULL;
     char* token = strtok_s(tempText, DELIMS, &context);
 ​
     while (token != NULL) {
         int found = 0;
 ​
         for (int j = 0; j < *uniqueCount; ++j) {
 ​
             if (strcmp(token, uniqueWords[j]) == 0) {
                 found = 1;
                 break;
             }
 ​
         }
         if (!found) {
             strcpy_s(uniqueWords[*uniqueCount], WORD_SIZE, token);
             (*uniqueCount)++;
         }
         token = strtok_s(NULL, DELIMS, &context);
     }
 ​
 }

[C语言大师:编得狂,骂得响后篇]哔哩哔哩bilibili]

你可能感兴趣的:(单片机,stm32,嵌入式硬件)