Calculate the length of the last word of the string, the words are separated by spaces, and the length of the string is less than 5000. (Note: The end of the string does not end with a space)

Table of contents

1. C language code implementation

2. Detailed explanation of some c language library functions

1.EOF

2. fgets function

3.stdin

4.strrchr

5th str

6.strlen()


Enter a description:

Enter a line, representing the string to be calculated, non-empty, and the length is less than 5000.

Output description:

Output an integer representing the length of the last word of the input string.

1. C language code implementation

#include <stdio.h> //printf, fgets, stdin
#include <string.h> //strrchr, strchr, strlen

int main(void)
{
    char str[5000] = {0};
    int length = 0;
    char *p = NULL;

    /* 使用fgets从标准输入(stdin)获取一行 */
    fgets(str, sizeof(str), stdin);

    /* 使用strrchr找到最右边的第一个空格 */
    p = strrchr(str, ' ');
    if (p)
        p = p + 1; //指向首字母
    else
        p = str; //只有一个单词

    /* 使用strchr查找是否存在换行符 */
    if (strchr(p, '\n'))
        length = strlen(p) - 1;
    else
        length = strlen(p);

    printf("%d\n", length);
    return 0;
}

pPoints to a string whose length can be strlenobtained using a function.

If there are multiple words in the input text, it ppoints to the first letter of the last word, and its length is the number of characters of the word, which can be obtained with strlen(p).

If there is only one word in the input text, it ppoints to the first letter of the entire string, and its length is the number of characters in the entire string, which can be obtained with strlen(str).

An array pointer is a pointer that points to the first address of an array. Pointers and arrays are closely related, you can get the first address of the array through the array name, and assign it to the pointer variable.

In C language, the array name itself is a pointer to the first address of the array, so the array name can be assigned to a pointer variable to obtain a pointer to the first address of the array.

The first bit of the array refers to the address of the first element in the array. Since the array is stored continuously in memory, the address of the first element is also the first address of the entire array. You can get the first address of the array through the array name or pointer, and then access other elements in the array through the offset.

2. Detailed explanation of some c language library functions

1.EOF

EOF (End of File) is a constant indicating the end of a file in C language. In C language, EOF is defined in the standard header file stdio.h, it is a negative integer constant, usually defined as -1.

EOF is usually used as a marker to indicate the end of the file, and can be used to check whether the end of the file has been reached when reading input. On standard input, EOF is returned when the user enters an end-of-file character (usually Ctrl+D on Unix systems and Ctrl+Z on Windows systems). EOF can also appear in a file as a special character, marking the end of the file.

2. fgets function

fgetsIs a function in the C standard library, which is used to read a line of string from the specified file stream and store it in the specified character array. Its function prototype is as follows:

char *fgets(char *str, int n, FILE *stream);

Among them, stris a pointer to a character array, used to store the read string; nis the maximum number of characters to be read, usually the length of the specified character array minus 1, in order to add an end marker to the string \0; streamis to The file stream to read, usually stdinmeans reading data from the standard input stream.

fgetsThe function reads data one line at a time, including newline characters, and stores it into the specified character array. If the length of the read string is greater than the specified maximum number of characters n, the function will only read n-1characters and leave the remaining characters in the input buffer for the next read.

fgetsThe function returns a pointer to a character array pointing to strthe read string stored in . fgetsThe function returns if end-of-file is read or an error occurs NULL.

3.stdin

stdinIs a file pointer defined in the C standard library, used to represent the standard input stream (standard input stream). In C, stdinpoints to a standard input device, usually the keyboard, that can be used to read user input.

By using stdinfile pointers, data can be read from the keyboard or other standard input devices and passed to a program. stdinIt is often used in C programs to allow the program to interact with the user, such as reading commands or data entered by the user. Using stdinpointers is a convenient way to read input from the console or command line, and to process input data.

4.strrchr

The full name is "string reverse find character", and its function is to find the position of the specified character in a string from back to front . strrchr is a C standard library function that is used to find the last occurrence of a specified character in a string. The strrchrfunction returns a pointer type, pointing to a certain position in the string, not the value of the character itself. The function prototype is as follows:

char *strrchr(const char *s, int c);

where s is the string to search for and c is the character to look for .

The function returns a pointer to the last occurrence of the character c , or NULL if c does not occur in s .

For example, the following code demonstrates how to use the strrchr function to find the position of the last "o" in a string:

char str[] = "Hello, World!";
char *p = strrchr(str, 'o');
if (p)
    printf("Last 'o' found at position %ld.\n", p - str);
else
    printf("'o' not found in the string.\n");

The output is:

Last 'o' found at position 8.

In this example, the pointer p points to the position of the last character "o" in the string, and the index of this position in the string can be calculated using pointer subtraction. p - strThe calculation method is to subtract the address pointed to by the pointer str from the address pointed to by the pointer p to obtain the address difference between them. The unit of this difference is the size of a character (usually a byte), that is to say , how many characters differ between them. In this particular example, p points to the position of the last 'o' in the string str, and str is the first address of the string, so the result p - stris the difference between the position of the last 'o' in the string and the first address of the string. number of characters between. Since the index of this position is counted from 0, the final output result needs to add 1 to get the actual position of the last 'o'. strThe value of the variable is "Hello, World!"that it is a character array that stores all the characters of this string, including the final null terminator. The value of the variable pis stra pointer to the last character 'o' in the string , specifically, it points to the 8th character in the string because characters are indexed from 0 in a string. Since the variable pis found by strrchrthe function, its value depends on strrchrthe return value of the function. If the specified character is found in the string, the pointer to the last occurrence of the character in the string is returned; if not found, Returns a null pointer (NULL). Since there are two characters 'o' in the string, and strrchrthe function will find the position of the last character 'o', the pvalue of the variable should be a pointer to the character 'o' in the string, which is strthe 8th character in the array The address of an element, so to speak &str[7].

5th str

strchrThe function is one of the string functions in the C language. Its function is to find the first occurrence of a specified character in a string .

strchrThe declaration of the function is as follows:

char *strchr(const char *str, int c);

where stris the string to look for and cis the character to look for. This function returns a pointer to the position of the first occurrence of the specified character. If the specified character is not found, the function returns a null pointer (NULL).

Here is a strchrsample code using the function:

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

int main() {
    char str[] = "hello, world";
    char *p;

    p = strchr(str, 'w');
    if (p != NULL) {
        printf("Found '%c' at position %ld\n", *p, p - str);
    } else {
        printf("Not found\n");
    }

    return 0;
}

This program first defines a string str, and then calls strchrthe function to find the first occurrence of the character 'w' in the string. If found, the program outputs the character's position in the string; otherwise, it outputs "Not found".

It should be noted that strchrthe function will only find the first occurrence of the specified character in the string. If you need to find all locations, you can use strstra function.

6.strlen()

strlen()is a function in the C standard library that determines the length of a null-terminated string. It takes one parameter, a pointer to a null-terminated string, and returns an integer value representing the length of the string. Here is an example:

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

int main() {
    char str[] = "Hello, world!";
    int len = strlen(str);
    printf("字符串的长度为 %d\n", len);
    return 0;
}

In this example, strlen()to determine "Hello, world!"the length of a string. lenThe value of will be 13, the number of characters in the string, not including the null terminator. Note that the function only works with null-terminated strings, so it's important to make sure your string is properly terminated with a null character ( ) strlen()before passing it to .strlen()'\0'

Guess you like

Origin blog.csdn.net/qq_44732869/article/details/130192916