当前位置:网站首页>C Primer Plus Chapter 11_ Strings and string functions_ Codes and exercises
C Primer Plus Chapter 11_ Strings and string functions_ Codes and exercises
2022-06-27 06:09:00 【Holding hands to listen to falling flowers】
11.1 Represents a string and a string I/O
Strings are empty characters (\0) At the end of the char Type data .
strings1.c Demonstrates several ways to represent strings in a program
#include <stdio.h>
#define MSG "I am a symbolic string constant."
#define MAXLENGTH 81
int main(void)
{
char words[MAXLENGTH] = "I am a string in an array.";
const char* pt1 = "Something is pointing at me.";
puts("Here are some strings:");
puts(MSG);
puts(words); /* puts Function displays only strings , And add a newline character to the end of the displayed string */
puts(pt1);
words[8] = 'p';
puts(words);
printf("%s, %p, %c\n", "We", "are", *"space farers");
return 0;
}
Define a string in a program
(1) Literal of a string ( String constant )
The contents enclosed in double quotation marks are called string literals . The characters in double quotes and the compiler automatically add the ending \0 character , Are stored in memory as strings .
String constants belong to the static storage category (static storage class), This shows that string constants are used in functions , The string will only be stored once , Throughout the life of the program , Even if the function is called more than once .
The contents enclosed in double quotation marks are interpreted as pointers to the storage location of the string .
(2) String array and initialization
const char m1[40] = "Limit yourself to one line's worth.";
const char m2[] = "Limit yourself to one line's worth."; /* It is recommended to use... When initializing a pointer to a string literal const qualifiers */
Let the compiler calculate the size of the array only when initializing the array .
const char * pt1= “Limit yourself to one line’s worth.”;
Be careful : The difference between an array and a pointer
Array name m2 Is a constant , Pointer name pt1 It's a variable. . If you want to modify the string , Don't point to a string literal with a pointer .
Initialization array copies the string of static storage area into the array , The initialization pointer only copies the address of the string to the pointer .
#include <stdio.h>
#define MSG "I'm special"
int main(void)
{
char ar[] = MSG;
const char* pt = MSG;
printf("address of \"I'm special\":%p \n", "I'm special");
printf(" address ar:%p\n", ar);
printf(" address pt:%p\n", pt);
printf(" address of MSG:%p\n", MSG);
printf("address of \"I'm special\":%p \n", "I'm special");
return 0;
}
(4) Array of strings
arrchar.c– Pointer to string data and char An array of type arrays
#include <stdio.h>
#define SLEN 40
#define LIM 5
int main(void)
{
const char* mytalents[LIM] = {
"Adding number swiftly",
"Multiplying accurately", "Stashing data",
"Following instrcutions to the letter",
"Understanding the C language"
};
char yourtalents[LIM][SLEN] = {
"Walking in a straight line",
"Sleeping", "Watching televisions",
"Mailing letters", "Reading email"
};
int i;
puts("Let's compare talents.");
printf("%-36s %-25s\n", "My talents", "Your talents");
for (i = 0; i < LIM; i++) {
printf("%-36s %-25s\n", mytalents[i], yourtalents[i]);
}
printf("\nsizeof mytalents: %zd, sizeof yourtalents: %zd\n",
sizeof(mytalents), sizeof(yourtalents));
return 0;
}
in summary , If you want to use an array to represent a series of strings to be displayed , Please use pointer array , Because it is more efficient than two-dimensional character array . however , Pointer arrays also have their own disadvantages .mytalents The literal of the string pointed to by the pointer in cannot be changed ; and yourtalentsde The contents of can be changed . therefore , If you want to change the string or reserve space for string input , Do not use pointers to string literals .
11.2 String input
If you want to read a string into the program , First, you must reserve space for storing the string , Then use the input function to get the string .
gets function
C11 The Standards Committee took a tougher stance , Directly removed from the standard gets() function .
The problem is gets() The only parameter is words, It cannot check whether the array can hold the input line . The last chapter introduced , The array name will be converted to the address of the first element of the array , therefore ,gets() Function only knows the beginning of the array , I don't know how many elements there are in the array .
“Segmentation fault”( Segmentation error ) It doesn't seem like a good tip , That's true . stay UNIX In the system , This message indicates that the program is trying to access unallocated memory .
#include <stdio.h>
#include <string.h>
#define STLEN 81
int main(void)
{
char words[STLEN];
puts("Enter a string, please.");
gets(words);
printf("Your string twice:\n");
printf("%s\n", words);
puts(words);
puts("Done.");
return 0;
}
fgets() and fputs() The usage function
fgets() The function of the first 2 Two parameters indicate the maximum number of characters to read in . If the value of the parameter is n, that fgets() Will read in n-1 Characters , Or read until the first line break you encounter .
If fgets() Read a newline , It's stored in a string . With this gets() Different ,gets() Line breaks are discarded .
fgets() The function of the first 3 A parameter indicates the file to be read in . If you read in the data entered from the keyboard , with stdin( The standard input ) As a parameter , The identifier is defined in stdio.h in
#include <stdio.h>
#include <string.h>
#define STLEN 14
int main(void)
{
char words[STLEN];
puts("Enter a string, please.");
fgets(words, STLEN, stdin); /* apple ie\n\0 Stored in an array */
printf("Your string twice(puts(), then fputs()):\n");
puts(words);
fputs(words, stdout); /* fputs() Don't add a newline at the end of the string */
puts("Enter another string, please.");
fgets(words, STLEN, stdin); /* fgets() Only read in 13 Characters , And put strawberry sh\0 Stored in an array . */
printf("Your string twice(puts(), then fputs()):\n");
puts(words); /* puts() The function adds a newline character at the end of the string to be output */
fputs(words, stdout);
puts("Done.");
return 0;
}
fgets() Function returns to char The pointer to . If everything goes well , The address returned by this function is the same as the address passed in 1 The two parameters are the same . however , If the function reads to the end of the file , It will return a special pointer : Null pointer (null pointer).
The following program demonstrates a simple loop , Read in and display user input , until fgets() Read the end of the file or an empty line ( namely , The first character is a newline character ).
#include <stdio.h>
#include <string.h>
#define STLEN 10
int main(void)
{
char words[STLEN];
puts("Enter strings (empty line to quit):");
while (fgets(words, STLEN, stdin) != NULL && words[0] != '\n') {
fputs(words, stdout);
}
puts("Done.");
return 0;
}
Read... For the first time By the wa\0
Second reading y, the ge\0
For the last time tion\n\0
fgets() Storing line breaks has both advantages and disadvantages . The downside is that you may not want to store line breaks in strings , Such line breaks can cause some trouble . The advantage is that for stored strings , Check whether there is a newline at the end to determine whether a whole line has been read . If it's not a whole line , To properly handle the remaining characters in a line .
First , How to deal with line breaks ? One way is to look for line breaks in the stored string , And replace it with empty characters :
while(words[i] != '\n') {
// hypothesis \n stay words in
i++;
}
words[i] = '\0';
secondly , What if there are still strings left on the input line ? One way to do this is to , If the target array cannot hold a whole line, enter , Just discard the extra characters :
while(getchar() != '\n') {
// Read but do not store input , Include \n
continue;
}
Program listing 11.9 In the program list 11.8 Added a part of test code on the basis of . The program reads the input line , Delete the newline character stored in the string , If there is no newline , Then discard the characters that the array cannot hold .
#include <stdio.h>
#include <string.h>
#define STLEN 10
int main(void)
{
char words[STLEN];
int i;
puts("Enter strings (empty line to quit):");
while (fgets(words, STLEN, stdin) != NULL && words[0] != '\n') {
i = 0;
while (words[i] != '\n' && words[i] != '\0') {
i++;
}
if (words[i] == '\n') {
words[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
puts(words);
}
puts("Done.");
return 0;
}
s_gets() function
If fgets() return NULL, It indicates that the end of the file is read or there is a reading error ,s_gets() The function skips the process .
If a newline character appears in the string , Just replace it with an empty character ;
If an empty character appears in the string , Discard the remaining characters of the input line , Then return to fgets() The same value .
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
Perhaps the reader wants to know why to discard the remaining characters in an overly long input line . This is because , Extra characters in the input line will be left in the buffer , Become the input of the next read statement . for example , If the next read statement is to read double Type value , It could cause the program to crash . Discarding the remaining characters in the input line ensures that the read statement is synchronized with the keyboard input .
scanf() function
scanf() Function has two ways to determine the end of input . Either way , All from the first 1 A non white space character is used as the beginning of the string . If you use %s Conversion instructions , The following is a blank character ( Blank line 、 Space 、 Tab or newline ) As the end of the string ( The string does not contain white space characters ). If field width is specified , Such as %10s, that scanf() Will read 10 Characters or read to the 1 Blank characters stop ( The first condition to be satisfied is the condition to end the input ).
scanf() Function returns an integer value , The value is equal to scanf() Number of items successfully read or EOF( When you read to the end of the file EOF).
Demonstrated in scanf() Function to specify the width of the field :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define STLEN 10
int main(void)
{
char name1[11], name2[11];
int count;
printf("Please enter 2 names.\n");
count = scanf("%5s %10s", name1, name2);
printf("I read the %d names %s and %s.\n", count, name1, name2);
return 0;
}
scanf() The typical use of is to read and convert mixed data types to some standard form . for example , If the input line contains a tool name 、 Inventory and unit price , You can use scanf(). Otherwise, you may have to piece together a function to handle some input checks . If you enter only one word at a time , use scanf() Also no problem .
scanf() and gets() similar , There are also some potential drawbacks . If the content of the input line is too long ,scanf() It can also lead to data overflow . however , stay %s The use of field widths in conversion instructions prevents overflow .
11.3 String output
puts() function
puts() Functions are easy to use , Just pass it the address of the string as a parameter .
puts() A newline character is automatically added at the end of the string when it is displayed .
puts() How to know where to stop ? This function stops printing when it encounters a null character , So you must make sure there are empty characters .
fputs() function
fputs() The function is puts() Customized version for files . The differences are as follows .
fputs() The function of the first 2 A parameter indicates the file to write data to . If you want to print on the monitor , Can be defined in stdio.h Medium stdout( standard output ) As this parameter .
And puts() Different ,fputs() No newline is added at the end of the output .
Be careful ,gets() Discard line breaks in input , however puts() Add line breaks to the output . On the other hand ,fgets() Keep line breaks in input ,fputs() Do not add line breaks to the output .
printf() function
And puts() The difference is ,printf() A newline character is not automatically added to the end of each string . therefore , You must indicate in the parameter where the newline character should be used .
Custom input \ Output function
Suppose you need a similar puts() But functions that do not automatically add line breaks .
void put1(const char* string)
{
while (*string != '\0') {
putchar(*string++); /* ++ Has a higher priority than * */
}
}
Suppose you want to design a similar puts() Function of , And the function also gives the number of characters to be printed .
int put1(const char* string)
{
int count = 0;
int i = 0;
while (string[i] != '\0') {
putchar(string[i++]);
count++;
}
putchar('\n'); // Do not count line breaks
return count;
}
Program listing 11.16 Test with a simple driver put1() and put2(), And demonstrates the call of nested functions .
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
void put1(const char* string);
int put2(const char* string);
int main(void)
{
put1("If i'd as much money");
put1(" as I could spend,\n");
printf("I count %d characters.\n",
put2("I never would cry old chairs to mend."));
return 0;
}
void put1(const char* string)
{
while (*string != '\0') {
putchar(*string++);
}
}
int put2(const char* string)
{
int count = 0;
while (*string != '\0') {
putchar(*string++);
count++;
}
putchar('\n');
return count;
}
String function
strlen() function
strlen() Function to count the length of a string . The following function can shorten the length of the string , Which USES strlen():
void fit(char* string, unsigned int size)
{
if (strlen(string) > size) {
string[size] = '\0';
}
}
Program listing 11.17 The program tested fit() function . Notice that the code uses C Concatenation property of string constants .
/* test_fit.c – Use a function to shorten the length of the string */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
void fit(char* string, unsigned int size);
int main(void)
{
char mesg[] = "Things should be as simple as possible,"
" but not simpler.";
puts(mesg);
fit(mesg, 38);
puts(mesg);
puts("Let's look at some more of the string.");
puts(mesg + 39);
return 0;
}
void fit(char* string, unsigned int size)
{
if (strlen(string) > size) {
string[size] = '\0';
}
}
strcat() function
strcat()( Used to concatenate strings ) Function takes two strings as arguments . This function puts the number 2 A backup of a string is attached to 1 At the end of a string , The new string formed after splicing is used as the second string 1 A string , The first 2 A string does not change .strcat() The type of function is char ( namely , Point to char
The pointer to ).strcat() Function returns the second 1 Parameters , That is to say, splice the second 2 The... After the first string 1 Address of a string .
/ str_cat.c – Concatenate two strings */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define SIZE 80
char* s_gets(char* st, int n);
int main(void)
{
char flower[SIZE];
char addon[] = "s smell like old shoes.";
puts("what is your favorite flower?");
if (s_gets(flower, SIZE)) {
strcat(flower, addon);
puts(flower);
puts(addon);
}
else {
puts("End of file encounted!");
}
puts("Bye.");
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
strncat() function
strcat() Function can't check section 1 Whether an array can hold the 2 A string . If assigned to 1 There is not enough space for arrays , When the extra characters overflow to the adjacent storage unit, there will be a problem .
/* join_chk.c – Concatenate two strings , Check the 1 The size of an array */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define SIZE 30
#define BUGSIZE 13
char* s_gets(char* st, int n);
int main(void)
{
char flower[SIZE];
char addon[] = "s smell like old shoes.";
char bug[BUGSIZE];
int available;
puts("what is your favorite flower?");
s_gets(flower, SIZE);
if ((strlen(addon) + strlen(flower) + 1) <= SIZE) {
strcat(flower, addon);
}
puts(flower);
puts("what is your favorite bug?");
s_gets(bug, BUGSIZE);
available = BUGSIZE - strlen(bug) - 1;
strncat(bug, addon, available);
puts(bug);
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
strcmp() function
strcmp() The function compares strings , Not the whole array .
ASCII The standard stipulates , In the alphabet , If the first 1 The first string is in 2 Before a string ,strcmp() Return a negative number ; If two strings are the same ,strcmp() return 0; If the first 1 The first string is in 2 After a string ,strcmp() Return positive number . However , The exact value returned depends on the implementation .
What happens if the first few characters of two strings are the same ? generally speaking ,strcmp() Will compare each character in turn , Until the discovery of the second 1 For different characters . then , Returns the corresponding value .
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define ANSWER "Grant"
#define SIZE 40
char* s_gets(char* st, int n);
int main(void)
{
char try[SIZE];
puts("Who is buried in Grant's tomb?");
s_gets(try, SIZE);
while (strcmp(try, ANSWER)) {
puts("No, that's wrong. Try again.");
s_gets(try, SIZE);
}
puts("That's right!");
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
use strcmp() Function to check whether the program wants to stop reading input .
The program reads EOF character ( In this case s_gets() return NULL)、 User input quit Or the input item reaches LIM Exit from time .
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define STOP "quit"
#define SIZE 80
#define LIM 10
char* s_gets(char* st, int n);
int main(void)
{
char input[LIM][SIZE];
int ct = 0;
/* ct < LIM && s_gets(input[ct], SIZE) != NULL && input[ct][0] != '\0' */
printf("Enter up to %d lines (type line to quit):\n", LIM);
while (ct < LIM && s_gets(input[ct], SIZE) != NULL &&
strcmp(input[ct], STOP) != 0) {
ct++;
}
printf("%d strings entered\n", ct);
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
strncmp() function
strcmp() The function compares characters in a string , Until you find different characters , This process may continue until the end of the string . and strncmp() Function when comparing two strings , Can be compared to different characters , You can also compare only the second 3 The number of characters specified by the . for example , To find to "astro" Starting string , You can restrict the function to find only this 5 Characters . Program listing 11.24 Demonstrates the usage of this function .
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define STOP "quit"
#define LISTSIZE 6
char* s_gets(char* st, int n);
int main(void)
{
const char* list[LISTSIZE] = {
"astronomy", "astounding",
"astrophsics", "ostracize",
"asterism", "astrophobia"
};
int count = 0;
int i;
for (i = 0; i < LISTSIZE; i++) {
if (strncmp(list[i], "astro", 5) == 0) {
printf("Found : %s\n", list[i]);
count++;
}
}
printf("The list contained %d words beginning"
" with astro.\n", count);
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
strcpy() and strncpy() function
strcpy() The order of the parameters , That is to say 1 One is the target string , The first 2 One is the source string .
It is the programmer's responsibility to ensure that the target array has enough space to hold copies of the source string .
strcpy() Takes two string pointers as arguments , You can point to the first... Of the source string 2 A pointer is declared as a pointer 、 Array name or string constant ; And point to the... Of the copy of the source string 1 A pointer should point to a data object ( Such as , Array ), And the object has enough space to store a copy of the source string . remember , Declare that the array will allocate space for storing data , The declaration pointer only allocates space for storing one address .
/* Require user input to q The first word . The program copies the input to a temporary array , If the first 1 One letter is q, Program call strcpy() Copy the entire string from the temporary array to the target array .strcpy() Function is equivalent to string assignment operator .*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define LIM 5
#define SIZE 40
char* s_gets(char* st, int n);
int main(void)
{
char qwords[LIM][SIZE];
char temp[SIZE];
int i = 0;
printf("Enter %d words beginning with q:\n", LIM);
while (i < LIM && s_gets(temp, SIZE) != NULL) {
if (temp[0] != 'q') {
printf("%s doesn't begin with q!\n", temp);
}
else {
strcpy(qwords[i], temp);
i++;
}
}
puts("Here are the words accepted:");
for (i = 0; i < LIM; i++) {
puts(qwords[i]);
}
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
strcpy() The function also has two useful properties . First of all ,strcpy() The return type of is char *, This function returns the number 1 The value of parameters , The address of a character . second , The first 1 The first argument doesn't have to point to the beginning of the array . This property can be used to copy part of the array .
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define WORDS "beast"
#define SIZE 40
char* s_gets(char* st, int n);
int main(void)
{
const char* orig = WORDS;
char copy[SIZE] = "Be the best that you can be.";
char* ps;
puts(orig);
puts(copy);
ps = strcpy(copy + 7, orig);
puts(copy);
puts(ps);
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
strncpy(target, source, n) hold source Medium n Characters before characters or empty characters ( Copy to where you meet the conditions first ) Copy to target in . therefore , If source The number of characters in is less than n, Then copy the whole string , Include empty characters . however ,strncpy() The length of the copy string will not exceed n, If you copy to the n The full source string has not been copied when characters are , You won't copy empty characters . therefore , There may not be empty characters in the copy . In view of this , The program puts n Set to less than the target array size 1(TARGSIZE-1), Then set the last element of the array to null character :
strncpy(qwords[i], temp, TARGSIZE - 1);
qwords[i][TARGSIZE - 1] = '\0';
This ensures that a string is stored . If the target space can hold a copy of the source string , Then the null character copied from the source string is the end of the copy ; If the target space can't hold copies , Set the last element of the copy to the null character .
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define LIM 5
#define SIZE 40
#define TARGSIZE 7
char* s_gets(char* st, int n);
int main(void)
{
char qwords[LIM][SIZE];
char temp[SIZE];
int i = 0;
printf("Enter %d words beginning with q:\n", LIM);
while (i < LIM && s_gets(temp, SIZE) != NULL) {
if (temp[0] != 'q') {
printf("%s doesn't begin with q!\n", temp);
}
else {
strncpy(qwords[i], temp, TARGSIZE - 1);
qwords[i][TARGSIZE - 1] = '\0';
i++;
}
}
puts("Here are the words accepted:");
for (i = 0; i < LIM; i++) {
puts(qwords[i]);
}
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
sprintf() function
This function and printf() similar , But it's writing data into strings , Instead of printing on the monitor .sprintf() Of the 1 The first parameter is the destination string
site . The rest of the parameters and printf() identical , That is, the format string and the list of items to be written .
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define MAX 20
char* s_gets(char* st, int n);
int main(void)
{
char first[MAX];
char last[MAX];
char formal[2 * MAX + 10];
double prize;
puts("Enter your first name:");
s_gets(first, MAX);
puts("Enter your last name:");
s_gets(last, MAX);
puts("Enter your prize money:");
scanf("%lf", &prize);
sprintf(formal, "%s, %-19s: $%6.2f\n", last, first, prize);
puts(formal);
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
String example : String sort
The subtlety of the program is that it sorts pointers to strings , Not the string itself .
We use the selective sorting algorithm (selection sort algorithm) To sort pointers . The specific way is , utilize for The loop compares each element to the first element in turn . If the element to be compared is in front of the current first element , Then exchange the two . At the end of the loop , The first element contains a pointer to the first string in the machine sort sequence . And then the outer layer for The cycle repeats the process , This time from input Of the 2 Elements start . When the inner loop is finished ,ptrst No 2 Elements point to at number one 2 String . This process continues until all elements have been sorted .
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define SIZE 81
#define LIM 20
char* s_gets(char* st, int n);
void stsrt(char* strings[], int num);
int main(void)
{
char input[LIM][SIZE];
char* ptstr[LIM];
int ct = 0;
int k;
printf("Input up to %d lines, and I will sort them.\n", LIM);
printf("To stop, press the Enter key at a line's start.\n");
while (ct < LIM && s_gets(input[ct], SIZE) != NULL &&
input[ct][0] != '\0') {
ptstr[ct] = input[ct];
ct++;
}
stsrt(ptstr, ct);
puts("\nHere's the sorted list:\n");
for (k = 0; k < ct; k++) {
puts(ptstr[k]);
}
return 0;
}
void stsrt(char* strings[], int n)
{
int i, j;
char* temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (strcmp(strings[i], strings[j]) > 0) {
temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
}
}
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
ctype.h Character functions and strings
The first 7 The chapter introduces ctype.h Series of functions related to characters . Although these functions cannot handle the entire string , But you can handle characters in strings . for example , Program listing 11.30 As defined in ToUpper() function , utilize toupper() The function processes each character in a string , Convert the entire string to uppercase ; Defined PunctCount() function , utilize ispunct() Count the number of punctuation marks in the string . in addition , The program uses strchr() Handle fgets() Read the newline character of the string ( If any ).
/* mod_str.c – Modify string */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LIMIT 81
char* s_gets(char* st, int n);
void ToUpper(char* str);
int PunctCount(const char* str);
int main(void)
{
char line[LIMIT];
char* find;
puts("Please enter a line:");
fgets(line, LIMIT, stdin);
find = strchr(line, '\n');
if (find) {
*find = '\0';
}
ToUpper(line);
puts(line);
printf("That line has %d punctuation characters.\n", PunctCount(line));
return 0;
}
void ToUpper(char* str)
{
while (*str) {
*str = toupper(*str);
str++;
}
}
int PunctCount(const char* str)
{
int ct = 0;
while (*str) {
if (ispunct(*str)) {
ct++;
}
str++;
}
return ct;
}
Convert a string to a number
Numbers can be stored as strings , It can also be stored in numerical form . Storing numbers as strings is storing numeric characters . for example , Numbers 213 With ’2’、‘1’、‘3’、'\0’ Is stored in a string array . Store... In numerical form 213, It's stored int Type value .
C Numerical operation is required in numerical form ( Such as , Addition and comparison ). But displaying numbers on the screen requires string form , Because the screen shows characters .printf() and sprintf() function , adopt %d And other conversion instructions , Convert a number from a numeric form to a string form ,scanf() You can convert the input string to numeric form .C There are also functions designed to convert string form to numeric form .
Suppose you write a program that uses numeric command parameters , But the command shape parameter is read as a string . therefore , To use a numeric value, you must first convert the string to a number . If you need an integer , have access to atoi() function ( Used to convert alphanumeric numbers to integers ), This function takes a string as an argument , Returns the corresponding integer value . Program listing 11.32 The program example in demonstrates the usage of this function .
/* hello.c – Convert command line arguments to numbers */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
int i, times;
if (argc < 2 || (times = atoi(argv[1]) < 1)) {
printf("Usage: %s positive-number\n", argv[0]);
}
else {
for (i = 0; i < times; i++) {
puts("Hello, good looking!");
}
}
return 0;
}
If the string only starts with an integer ,atio() Functions can also handle , It only converts the first integer into characters . for example , atoi(“42regular”) Will return an integer 42.atof() The function converts a string to double Type value , atol() The function converts a string to long Type value .atof() and atol() How it works and atoi() similar , So they return... Separately double The type and long type .
ANSI C It also provides a set of smarter functions :strtol() Converts a string to long Type value ,strtoul() Converts a string to unsigned long Type value ,strtod() Converts a string to double Type value . The intelligence of these functions is to recognize and report that the first character in a string is
No, it's a number . and ,strtol() and strtoul() You can also specify the base number of digits .
The following program example involves strtol() function , Its prototype is as follows :
long strtol(const char * restrict nptr, char ** restrict endptr, int base);
here ,nptr Is a pointer to the string to be converted ,endptr It's the address of a pointer , The numeric address of the input character is set to ,base Indicates the base in which the number is written . Program listing 11.33 Demonstrates the usage of this function .
/* strcnvt.c – Use strtol() */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LIM 30
char* s_gets(char* st, int n);
int main(int argc, char *argv[])
{
char number[LIM];
char* end;
long value;
puts("Enter a number (empty line to quit):");
while (s_gets(number, LIM) && number[0] != '\0') {
value = strtol(number, &end, 10); // Decimal system
printf("base 10 input, base 10 output: %ld, stopped at %s (%d)\n",
value, end, *end);
value = strtol(number, &end, 16); // Hexadecimal
printf("base 16 input, base 10 output: %ld, stopped at %s (%d)\n",
value, end, *end);
puts("Next number:");
}
puts("Bye!");
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val != NULL) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') {
st[i] = '\0';
}
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
Review questions 1. What's wrong with the declaration of the following string ?
int main(void)
{
char name[] = {‘F’, ‘e’, ‘s’, ‘s’ };
…
}
2. What will the following program print ?
#include <stdio.h>
int main(void)
{
char note[] = “See you at the snack bar.”;
char *ptr;
ptr = note;
puts(ptr);
puts(++ptr);
note[7] = ‘\0’;
puts(note);
847
puts(++ptr);
return 0;
}
3. What will the following program print ?
#include <stdio.h>
#include <string.h>
int main(void)
{
char food [] = “Yummy”;
char *ptr;
ptr = food + strlen(food);
while (–ptr >= food)
puts(ptr);
return 0;
}
4. What will the following program print ?
#include <stdio.h>
#include <string.h>
int main(void)
848
{
char goldwyn[40] = "art of it all ";
char samuel[40] = “I read p”;
const char * quote = “the way through.”;
strcat(goldwyn, quote);
strcat(samuel, goldwyn);
puts(samuel);
return 0;
}
5. The following exercise covers strings 、 loop 、 Pointer and increment pointer . First , Suppose the following function is defined :
#include <stdio.h>
char *pr(char *str)
{
char *pc;
pc = str;
while (pc)
putchar(pc++);
do {
849
putchar(–pc);
} while (pc - str);
return (pc);
}
Consider the following function call :
x = pr(“Ho Ho Ho!”);
a. What will be printed ?
b.x What type is it ?
c.x What is the value of ?
d. expression –pc What does that mean? ? And –pc What's the difference? ?
e. If you use –pc Replace –*pc, What will be printed ?
f. Two while What is the loop used to test ?
g. If pr() The argument to the function is an empty string , What will happen ?
h. What must be done in the calling function , To make pr() Function is working properly ?
6. Assume the following statement :
char sign = '$';
sign How many bytes of memory does it take ?' ′ Occupy use many Less word section Of Inside save ? " ' How many bytes of memory does it take ?" ′ Occupy use many Less word section Of Inside save ?"" How many bytes of memory does it take ?
7. What will the following program print out ?
8. What will the following program print out ?
9. As defined in this chapter s_gets() function , Using pointer notation instead of array notation can reduce one variable i. Please rewrite this function .
10.strlen() The function takes a pointer to a string as an argument , And returns the length of the string . Please write such a function .
11. As defined in this chapter s_gets() function , It can be used strchr() Function instead of while Loop to find line breaks . Please rewrite this function .
12. Design a function , Accept a pointer to a string , Returns a pointer to the... Of the string 1 A pointer to a space character , Or if the space character is not found , Return null pointer .
13. Rewrite the program list 11.21, Use ctype.h Functions in header file , So that whether the user selects uppercase or lowercase , The program can correctly identify the answer .
Programming practice
1. Design and test a function , Get the next... From the input n Characters ( Including blanks 、 tabs 、 A newline ), Store the results in an array , Its address is passed as a parameter .
2. Modify and program exercises 1 Function of , stay n Stop after two characters , Or after reading the 1 Blank 、 Stop on tab or newline , Which comes first and which stops . You can't just use scanf().
3. Design and test a function , Read a word from one line of input into an array , And discard the remaining characters in the input line . This function should skip the second 1 All whitespace before a non whitespace character . Define a word as having no blanks 、 A character sequence of tabs or line breaks .
4. Design and test a function , It is similar to programming practice 3 Description of , Only it accepts the first 2 A parameter indicates the maximum number of characters that can be read .
5. Design and test a function , Search page 1 A string specified by a function parameter , Look for the second 2 Where the character specified by a function parameter first appears . If it works , This function returns a pointer to the character , If the specified character is not found in the string , Return null pointer ( The function is similar to strchr() The same function ). Test the function in a complete program , Use a loop to provide input values to the function .
6. Write a project called is_within() Function of , Take a character and a pointer to a string as two function parameters . If the specified character is in a string , This function returns a non-zero value ( It's true ). otherwise , return 0( False ). Test the function in a complete program , Use a loop to provide input values to the function .
7.strncpy(s1, s2, n) Function s2 Medium n Copy characters to s1 in , truncation s2, Or add an empty character at the end if necessary . If s2 Is the length of the n Or more than n, The destination string cannot end with a null character . This function returns s1. Write such a function yourself , be known as mystrncpy(). Test the function in a complete program , Use a loop to provide input values to the function .
8. Write a project called string_in() Function of , Take two pointers to a string as arguments . If the first 2 The first string contains 1 A string , This function will return the second 1 The address at the beginning of a string . for example ,string_in(“hats”, “at”) Will return hats in a The address of . otherwise , This function returns a null pointer . Test the function in a complete program , Use a loop to provide input values to the function .
9. Write a function , Replace the contents of a string with its inverted string . Test the function in a complete program , Use a loop to provide input values to the function .
10. Write a function that takes a string as an argument , And delete the spaces in the string . Test the function in a program , Use a loop to read the input line , Until the user enters a blank line . The program should apply the function only to each input string , And display the processed string .
11. Write a function , Read in 10 A string or read EOF Stop when . The program provides users with a 5 A menu of options : Print a list of source strings 、 With ASCII Print strings in the order in 、 Print strings in ascending order of length 、 Press the second in the string 1 Print a string with a length of words 、 sign out . The menu can be displayed circularly , Unless the user chooses the exit option . Of course , The program should be able to truly complete the functions of various options in the menu .
12. Write a program , Read input , Until I read EOF, Report the number of words read 、 Capital letters 、 Lowercase letters 、 The number of punctuation marks and numeric characters . Use ctype.h Functions in header file .
13. Write a program , Displays the words of the command line arguments in reverse order . for example , The command line arguments are see you later, The program should print later you see.
14. Write a program running through the command line to calculate the power . The first 1 The first command line argument is double Number of types , As the base of a power , The first 2 The first parameter is an integer , The exponent as a power .
15. Using character classification function atoi() function . If the input string is not a pure number , This function returns 0.
16. Write a program to read input , Until the end of the file is read , Then print out the string . The program recognizes and implements the following command line parameters :
-p Print as is
-u Convert all input to uppercase
-l Convert all input to lowercase
If there are no command line arguments , Make the program seem to use -p Parameters .
边栏推荐
- 汇编语言-王爽 第13章 int指令-笔记
- My opinion on test team construction
- The form verifies the variables bound to the V-model, and the solution to invalid verification
- tar: /usr/local:归档中找不到tar: 由于前次错误,将以上次的错误状态退出
- IAR systems fully supports Centrino technology 9 series chips
- 【QT小作】使用结构体数据生成读写配置文件代码
- Multithreading basic part2
- 【QT小点】实现看门狗功能,检测外部程序是否在运行
- 思维的技术:如何破解工作生活中的两难冲突?
- 主动学习(active learning)
猜你喜欢
Dev++ environment setting C language keyword display color
The risk of multithreading -- thread safety
Dev++ 环境设置C语言关键字显示颜色
Small program of C language practice (consolidate and deepen the understanding of knowledge points)
JVM class loading mechanism
JS to implement bidirectional data binding
Go log -uber open source library zap use
【QT小作】使用结构体数据生成读写配置文件代码
JVM的垃圾回收机制
研究生数学建模竞赛-无人机在抢险救灾中的优化应用
随机推荐
Change the status to the corresponding text during MySQL query
TiDB 基本功能
Inter thread wait and wake-up mechanism, singleton mode, blocking queue, timer
【养成系】常用正则表达式
[QT notes] simple understanding of QT meta object system
【Cocos Creator 3.5.1】event. Use of getbutton()
TiDB的使用限制
创建一个基础WDM驱动,并使用MFC调用驱动
Database - index
Assembly language - Wang Shuang Chapter 3 notes and experiments
MATLAB快速将影像的二维坐标转换为经纬度坐标
JVM常用指令
Gaussian distribution, linear regression, logistic regression
使用CSDN 开发云搭建导航网站
软件测试年终总结报告模板
JVM对象组成和存储
TiDB 中的视图功能
免费的 SSH 和 Telnet 客户端PuTTY
JVM tuning ideas
高斯分布Gaussian distribution、线性回归、逻辑回归logistics regression