08- c language string (C language)

The definition and basic use of a string

1. What is a string

A collection of characters quoted by double quotes! For example: "hello", "world", or a character array ending with '\0' ! ! !
For example: char ch[] = {'h', 'e', ​​'\0'}
Note: "hello" actually has '\0' at the end , but we can see it.

That is to say: the string must end with '\0' ! !
How to verify that there is a character '\0' in "hello"?
printf("%d\n", *(p+5)); If the output result is an integer 0, it means that the end is '\0'

2. The relationship and difference between string and character array

Strings can be treated as character arrays, but character arrays may not necessarily be treated as strings. Why?
Because there is not necessarily '\0' in the character array.

char ch[] = {‘a’, 'b', '\0', 'c', 'd'};

In this case, we can treat the array ch as the string "ab".
In actual work, we often have the following requirements. We need to use a character array to store multiple characters, and we need to treat these multiple characters as strings. But when we define the character array, we only know the maximum number of characters that need to be saved (assumed to be 30), and the characters stored may be less than 30 during actual storage. How to ensure that these characters are treated as strings?

c har name[ 30 ] ;
memset(name, 0, sizeof(name));

Note: When defining the length of the character array, it is usually more than the actual number of bytes to be stored + 1 (because the last byte needs to be saved as ' \0 ').

3. String operations

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    //字符串的操作:
    char *str;
    char ch[] = {"hello"};
    str = ch;
    //可以通过指针str操作ch
    //方法1:
    str[1] = 'a'; //当一个指针指向了一个数组以后,我们就可以通过指针使用下标法直接访问数组中的元素
    //方法2:
    *(str + 1) = 'a';
    //也可以将字符串常量赋值给一个指针变量
    char *p = "hello";
    /*注意:p是一个指针变量,应该保存的是一个地址,因此 char *p = "hello"; 并不是将字符串"hello"赋值给
    指针变量p,而是将存储字符串 "hello"的内存空间的首地址赋值给p
    */
    return 0;
}

4. Assign each element in the character array to '\0'

#include <string.h>
void *memset(void *s, int c, size_t n);

memset function: fill n bytes in the memory space pointed to by the pointer s into c
sample code:

#include <stdio.h>
#include <string.h>

int main()
{
    char ch[10];
    memset(ch, 0, sizeof(ch)); //memset(ch, 0, sizeof(ch));
    printf("view the data ch: %d\n", ch[0]);
    return 0;
}

5. Please analyze what is wrong with the following code?

char *p = "hello";
p[0] = 'A';

Two common string processing functions

1. atoi function

#include <stdlib.h>
int atoi(const char *nptr);

Function: Convert a string to an integer of type int, and return the converted integer value.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    char *p = "1234";
    int val = atoi(p);
    printf("view the data: %d\n", val);
    return 0;
}

Exercise: Write code to implement the atoi function .

2. atof function

#include <stdlib.h>
double atof(const char *nptr)

Function: Convert a string to a floating-point number of double type , and return the converted floating-point number

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char *p = "123.456";
    double val = atof(p);
    printf("%f\n", val);
    return 0;
}

3. strlen function

#include <string.h>
size_t strlen(const char *s);

Function: Calculate the length of a string

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char *ch = "hello";
    char arr[] = {'A', 'B', 'C', '\0', 'D'};
    printf("%d %d\n", strlen(ch), strlen(arr));
    return 0;
}

Thinking: Why is the result of strlen(arr) 3?
Exercise: Programming to implement the strlen function

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    char *ch = "hello";
    char arr[] = {'A', 'B', 'C', '\0', 'D'};
    printf("%d  %d\n", strlen(ch), strlen(arr));
    return 0;
}

Thinking: Why is the result of strlen(arr) 3?
Exercise: Programming to implement the strlen function

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int my_strlen(char ch[]) //int my_strlen(char *ch)
{
    int cnt = 0;
    int i = 0;
    while (ch[i] != '\0')
    {
        cnt++;
        i++;
    }
    return cnt;
}

4. strcpy function

#include <string.h>
char *strcpy(char *dest, const char *src);

Function: Copy the character string pointed to by src to the space pointed to by dest, and '\0' will also be copied in the past
. Parameters:
dest : Destination character string first address
src : Source character first address
Return value:
Success: Return dest character string The first address
of failed: NULL

Sample code:

#include <stdio.h>
#include <string.h>

int main(){
    char *src = "hello";
    char dst[10] = {0};
    strcpy(dst, src);
    printf("src: %s, dst: %s\n", src, dst);
    return 0;
}

Note:
1. The space of dst must be larger than the space occupied by the content to be copied from src, at least 1 byte larger (because the space for '\0' is reserved).

#include <stdio.h>
#include <string.h>

int main(){
    char a[4];
    char b[4];  //hello
    strcpy(b, "hello");
    printf("view the data b: %s\n", b);  //hello
    printf("view the data a: %s\n", a);  //0
    return 0;
}

2. Implementation of strcpy

char *strcpy(char *dest, const char *src, size_t n){
    size_t i;
    for (i=0;i<n && src[i] != '\0'; i++)
        dest[i] = src[i];
    for (; i<n; i++)
        dest[i] = '\0';
    
    return dest;
}

5. strncpy function

#include <string.h>
char *strncpy(char *dest, const char *src, size_t n);

Function: Copy the first n characters of the string pointed to by src to the space pointed to by dest, whether to copy the terminator to see if the specified length contains '\0'.
Parameters:
dest: the first address of the destination string
src: the first address of the source character
n: specify the number of strings to be copied
Return value:
success: return the first address of the dest string
Failure: NULL

Note:
1. strncpy can copy up to n bytes . If there is no '\0' in the first n bytes, '\0' will not be copied in the end.
2. If the length of src is less than n, some '\' will be written 0' to ensure that a total of n Bytes are written. If strncpy already has '\0' in the previous n bytes when copying, it will only copy to '\0', but it will still continue to write to dest '\0' to ensure that a total of n Bytes are written.
Implementation of strncpy:

char *strncpy(char *dest, const char *src, size_t n){
    size_t i;
    for (i=0; i<n && src[i] != '\0'; i++)
        dest[i] = src[i];
    for (; i<n; i++)
        dest[i] = '\0';
    return dest;
}

6. The difference between strcpy and strncpy

If you can be 100% sure that the space of dest is larger than that of src , you can use strcpy. In actual work, we try to use strncpy
as much as possible to avoid overflow . Here comes the problem again! If n is larger than the size of the memory space pointed to by dest when using strncpy, won't it still cause overflow? So how to avoid this overflow situation? Method: first judge the length len of dest and the size of n , if len>=n, then copy n elements, if len<n, then copy len elements!

7. strcat function

#include <string.h>
char *strcat(char *dest, const char *src);

Function: connect the src string to the end of dest , and '\0' will also be appended.
Parameters:
dest: the first address of the destination string
src: the first address of the source character
Return value:
success: return the first address of the dest string
Failure: NULL
Sample code:

#include <stdio.h>
#include <string.h>

int main(){
    char ch[20];
    memset(ch, 0, sizeof(ch));

    strcpy(ch, "hello");
    strcat(ch, "world");
    printf("view the data: %s\n", ch);
    return 0;
}

Note: The space of ch must be large enough!
Implementation of strcat:

#include <stdio.h>
#include <string.h>

char *strncat(char *dest, const char *src, size_t n){
    size_t dest_len = strlen(dest);
    size_t i;
    
    for (i=0; i<n && src[i] != '\0'; i++)
        dest[dest_len + i] = src[i];
    dest[dest_len + i] = '\0';
    return dest;
}

8. strncat function

#include <string.h>
char *strcat(char *dest, const char *src);

Function: connect the src string to the end of dest , and '\0' will also be appended.
Parameters:
dest: the first address of the destination string
src: the first address of the source character
Return value:
success: return the first address of the dest string
Failure: NULL
Notice:

  • If the content length in src is m less than n bytes, then only m+1 bytes will be appended (a '\0' will be automatically appended at the end)
  • If the content length in src is m less than n bytes, then append n+1 bytes (a '\0' will be automatically appended at the end)

Sample code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    char *p;
    p = (char *)malloc(20);
    strcpy(p, "hello");
    strncat(p, "world", 3);
    printf("%s\n", p);

    memset(p, 0, 20);
    strcpy(p, "hello");
    strncpy(p, "world", 7);
    printf("%s\n", p);
    return 0;
}

Implementation of strcat :

char *strncat(char *dest, const char *src, size_t n){
    size_t dest_len = strlen(dest);
    size_t i;
    
    for (i=0; i<n && src[i] !='\0'; i++)
        dest[dest_len + i] = src[i];
    dest[dest_len + i] = '\0';
    return dest;
}

 The differences are summarized as follows:

  • strcatWill concatenate the source string in its entirety to the end of the destination string until the end character of the source string is encountered.
  • strncat Limits the number of concatenated characters , only the firstncharacter of the source string is concatenated.

9. strcmp function

#include <string.h>
int strcmp(const char *s1, const char *s2);

Function: The characters of two strings will be compared one by onestrcmp in lexicographical order . The comparison rules are as follows:

  • First compare the first characters of the two strings, and if they are equal, continue to compare the next characters.
  • If the characters at a certain position of the two strings are not equal, the comparison result is the ASCII code difference of the two characters.
  • If one of the strings has ended (a null character was encountered \0) and the other has characters remaining, the shorter string is considered to be smaller than the longer string.

parameter:

  • s1: string 1 first address
  • s2: String 2 first address

return value :

  • equal: 0
  • Greater than: >0 In different operating systems, strcmp results will be different and return the ASCII difference
  • less than: <0

Principle:
The execution logic of strcmp: Compare the characters in the corresponding positions in s1 and s2 one by one until the two strings are traversed completely (if no different characters are found, the two are equal), or there are two characters If they are not equal, the comparison ends. If the ASCII code of the character in s1 is larger than that in s2, return 1, otherwise return -1
Note: Some compilers have two strings

int main(){
    printf("%d\n", strcmp("hello", "hello"));  //前面等于后面,结果为0
    printf("%d\n", strcmp("hello", "heLlo"));  //前面大于后面,结果为1
    printf("%d\n", strcmp("Hello", "heLlo"));  //前面小于后面,结果为-1
    return 0;
}

10. strncmp function

#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n);

Function: compare the size of the first n characters of s1 and s2, and compare the ASCII code size of the characters.
parameter:

  • s1: string 1 first address
  • s2: String 2 first address

n: Specifies the number of comparison strings
Return value :

  • equal: 0
  • greater than: > 0
  • Less than: < 0

Exercise 1:
Input a string on the keyboard, and judge whether the string is equal to the string set in the program (up to 6 characters for comparison) (case insensitive)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    char ch1[10];
    char key[] = "A18Cd9";
    memset(ch1, 0, sizeof(ch1));
    printf("please input the key: %s\n", key);
    scanf("%s", ch1);
    printf("view the data ch1: %s\n", ch1);
    return 0;
}

Exercise 2:
Enter a string of strings on the keyboard, and delete the non-alphabetic and non-numeric characters!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    char ch1[10];
    memset(ch1, 0, sizeof(ch1));
    printf("plz input the data:\n");
    scanf("%s", ch1);
    printf("the data ch1: %s\n", ch1);
    return 0;
}

11. strstr function

strstris a string lookup function in C language, which is used to find the occurrence position of a substring in a string .

#include <string.h>
char *strstr(const char *haystack, const char *needle);

Function: Find the occurrence position of the string needle in the string haystack
Parameters:

  • haystack: the first address of the source string
  • needle: match the first address of the string

return value :

  • Success: returns the first occurrence of the needle address
  • Failed: NULL
  • We often use strstr to judge whether a string is another string!
int main(){
    char src[] = "ddddsabcd12233dsfl23dlf09a1";
    char *p = strstr(src, "abcd");
    printf("p = %s\n", p);
    return 0;
}

12. strtok function

strtokIt is a string splitting function in C language, which is used to split a string according to the specified delimiter .

#include <string.h>
char *strtok(char *str, const char *delim);

Function: to split the string into pieces. When strtok() finds the split character contained in the parameter delim in the string of parameter s, it will change the character to \0 character, and only replace the first one with \0 when there are more than one in a row.
parameter:

  • str: Points to the string to be split
  • delim: for all characters contained in the split string

return value :

  • Success: the first address of the string after splitting
  • Failed: NULL

Notice:

  • On the first call: strtok() must be given the parameter s string
  • Subsequent calls will set the parameter s to NULL, and each successful call will return a pointer to the divided segment
int main(){
    char a[100] = "abc-efg-hijk-lmn";
    char *s = strtok(a, "-");  //将"-”分割的子串取出
    while (s != NULL){
        printf("%s\n", s);
        s = strtok(NULL, "-");
        printf("view the s: %s\n", s);
    }
}

The complete code of string knowledge points:

int main(){
    //字符串的复制  strcpy
    /*char *src = "hello";

    char dst[10];
    strcpy(dst, src);
    printf("%s\n", dst);  //复制

    char a[4];
    char b[4];
    strcpy(b, "hello");
    printf("b: %s\n", b);
    printf("a: %s\n", a);*/

    /*char *src = "hello\0world";
    char dst[10];
    //char *dst;
    //dst = malloc(10);
    memset(dst, 'A', 10);
    printf("dst:%s\n", dst);    //AAAAAAAAAA
    strncpy(dst, src, 3);
    printf("dst: %s\n", dst);   //helAAAAAAA

    char *src1 = "hello";
    memset(dst, 0, 10);
    strncpy(dst, src, sizeof(dst)-1);
    printf("dst:%s\n", dst);    //hello

    int i;
    for (i=0; i<10; i++)
        printf("view the i: %d dst[i]: %c\n", i, dst[i]);
    printf("\n");*/


    //字符串的拼接 strcat
    /*char dst[20];
    memset(dst, 0, sizeof(dst));
    char *src = "he\0llo";
    strcpy(dst, "world");
    strcat(dst, src);
    printf("dst: %s\n", dst);  //worldhe */

    //字符串的对比
    //strcmp函数
    /*char *s1 = "hello world";
    char *s2 = "hello";
    printf("%d\n", strcmp(s2, s1));   //-1

    char *stus[] = {"zhangsan", "lisi", "wangwu", "liusan", "huangsan"};
    int i;
    for (i=0; i<3; i++){
        if (strcmp(stus[i], "lisi") == 0)
            printf("hello, lisi: %d\n", i);   //1
    }
    printf("view the data strncmp: %d\n", strncmp(s1, s2, 5));   //0 */


    //strstr函数  查找字符串内部是否存在某个元素
    /*char *stus[] = {"zhangsan", "lisi", "wangwu", "liusan", "huangsan"};
    int i;
    char *p;
    for (i=0; i<5; i++){
        //找出名字中带san的学生
        if (p = strstr(stus[i], "san")){
            printf("view the data, i: %d, stus[i]: %s\n", i, stus[i]);
            printf("%p, %p\n", stus[i], p);
        }
    }*/


    //字符串的分割  strtok
    char data[] = {"##name=zhangsan;score=99.5;age=10##"};
    //第一步用;分割
    char *p;
    int n = 0;
    int len;
    p = strtok(data, ";");
    printf("view the n: %s\n", p);  //##name=zhangsan

    len = strlen(p);
    while (*p != '=' && n<=len){
        printf("n:%d\n", n);
        p++;
        n++;
    }
    if (n <= len){
        p++;
        char name[10];
        memset(name, 0, 10);
        strcpy(name, p);
        printf("view the n: %d, len: %d, name: %s\n", n, len, name);  //zhangsan
    }


    //第二次对剩下的数据使用;分割
    char name[10];
    int age;
    float score;
    while (p = strtok(NULL, ";")){
        char *tmp = p;
        printf("%s\n", p);
        len = strlen(p);
        n = 0;
        while (*p != '=' && n<=len){
            p++;
            n++;
        }
        printf("view the data p: %c", p);
        if (n <= len){
            p++;
            if (strstr(tmp, "age=") != NULL){
                age = atoi(p);
                printf("age: %d\n", age);
            }
            else if (strstr (tmp, "score=") != NULL){
                score = atof(p);
                printf("score: %f\n", score);
            }
        }
    }

    p = strtok(NULL, ";");
    printf("view the strtok p: %s\n", p);
    len = strlen(p);
    n = 0;
    while (*p != '=' && n<=len){
        p++;
        n++;
    }
    if (n <= len){
        p++;
        int age;
        age = atoi(p);  //18
        printf("age: %d\n", age);
    }

    p = strtok(NULL, ";");
    printf("+++++ %s\n", p);
    len = strlen(p);
    n = 0;
    while (*p != '=' && n<=len){
        p++;
        n++;
    }
    if (n <= len){
        p++;
        float score;
        score = atof(p);
        printf("score: %f\n", score);
    }

    return 0;
}

Guess you like

Origin blog.csdn.net/March_A/article/details/131353756