Chapter 11 strings and string functions

11.1 represent strings and string I / O

String is the null character '\ 0' at the end of an array of type char

11.1 string is defined in the program ..

1. string literal (constant string)

Content with double quotation marks is referred to the amount of the word string, where '\ 0' is also stored as a character in a string.

ANSIC from the start, if there is no space between the string literal, or separated by whitespace, the string be regarded C concatenated.

String is a static storage class

2. initialization string array and

例:char n[] ;"hello"

3. arrays and pointers

An array: an opened space in the memory, each element is initialized to the corresponding character string.

That is, when the program starts running when the array will allocate space, this time, there are two copies of the string, a string literal static memory, and the other is an array of strings.

Pointer form: just create a storage location to a pointer variable, while the string is only a string literal that is still in memory, the pointer only stores the address of a string literal.

In short: the array initialization string is copied into the static memory array, only the copy initialization string pointer for the pointer.

4. The difference between the arrays and pointers

If the string is not modified, try not to use pointers to literal.

The array of strings

const  char *mytalents [n]={
        "qwerty"
        "qwertydf"
};
const  char yourtalents [n][m]={
        "qwerty"
        "qwertydf"
};

 

 Can mytalens as a rectangular two-dimensional array, the array yourtalens as irregular

To change the input string or strings reserved space do not use a pointer pointing to a string literal.

11.1.2 string pointer and

11.2 string input

11.2.1 allocated space

First allocate space

11.2.2 unfortunately gets () function

gets () only know the beginning of the array, the array does not know how many elements, input too long will cause a buffer overflow.

puts () automatically add a line break.

11.2.3 gets () alternatives

1.fgets()

The second argument specifies the maximum number of characters to read, if the parameter is n, n is greater than the size of the array, the read n-1 characters, then assign a '\ 0', n is less than the size of the array to print the first line breaks so far.

If n is less than the array size, fgets () to read a line break, it will be stored in the string, the gets () newline is discarded.

fgets () The third argument specifies the file to be read if the input data from the keyboard, the stdin (standard input)

This function returns a pointer pointing to char type, if successful, the same function and passing the first argument, if the read end of the file, it returns a null pointer.

FPUs () second parameter specifies the file to be written, displayed on a computer screen, is stdout.

2.gets_s function

The first parameter: Enter the name of the array, the second argument: the number of characters.

gets () to read a newline will discard it,

If gets () to read the maximum number of characters have not encountered a line break, it will target the first character in the array is set to null character, then reads and discards input until it encounters a newline or the end of the file.

3. s_gets () function

Read the entire line and replaced with a null character input line feed, or read input portion, and discards the rest.

char * s_gets ( char * ST, int   n-) 
{ 
    char * RET_VAL;
     int I = 0 ; 
    RET_VAL = fgets (ST, n-, stdin);
     IF (RET_VAL) // end of file indicates fgets not read successfully read 
  {
    the while (!! ST [I] = '\ O' && ST [I] = '\ n-')
      I ++;
    IF (ST [I] == '\ n-')
      ST [I] = '\ 0';
    the else
      the while (! getchar () = '\ n-')
        Continue;
   }
   return RET_VAL;
}

 

11.2.4 scanf () function

In the first non-blank character as the start, one of the following white space (spaces, blank lines, tabs, or line) as the end of the string.

11.3 string output

11.3.1 puts () function

the puts () will automatically add a newline character string in the display.

11.3.2 fputs () function

fputs () second parameter specifies the file to be written, displayed on a computer screen, is stdout. Not add a line break.

11.3.3 printf () function

11.4 Custom input and output functions

11.5 String Functions

11.5.1 strlen () function

Statistics string length

strlen () only one parameter encounter \ 0 End

11.5.2 strcat () function

A string concatenation, accepts two strings as arguments. The second string appended to the first string back up, (the first string \ 0 tone replacing) a second constant string.

This function returns the first argument. (I.e., a pointer to the first string)

11.5.3 strncat function

The maximum number of characters for the third parameter specifies the added

11.5.4 strcmp () function

Compares two strings, strcmp () comparing each character in turn, until it finds a first pair of different character, (ordered sequence according to machine) Returns the difference between two numbers.

strncmp () The third parameter is the number of characters specified comparison.

11.5.5  strcpy()和strncpy()

Copy the string, to assign a second parameter to the first parameter.

strcpy () Returns the type char *, the function returns a value of the first parameter.

strncpy () is the third parameter specifies the maximum number of characters can be copied.

11.5.6  sprintf()

sprintf () declared in stdio.h

The first argument is the address of the destination string, the next () printf and consistent use.

11.5.7 Other String Functions

char  *strcpy  (char*restrict  s1, const char*restrict  s2)

The above is the point s2 string (including null character) are copied to the location pointed to by s1, s1 return value

char  *strncpy  (char*restrict  s1, const char*restrict  s2,size_t  n)

The above is the point s2 string (including null character) are copied to the location pointed to by s1, the copy number of characters is not more than n, the return value s1.

If the source string is less than n, the destination string to the end of the empty string copy.

If more than n, not a copy of the null character.

char  *strcat  (char*restrict  s1, const char*restrict  s2)

The above is copied to the pointer to the string pointed to by s1 s2 end of the string, the first character string s2, s1 to cover the end of the null character string.

char  *strncat  (char*restrict  s1, const char*restrict  s2 , size_t  n)

The above is the string pointed to by s2 n characters are copied to the end of the string pointed to by s1, s2 first character, null character s1 to cover the end of the string.

char  *strcmp  (const char* s1, const char*  s2)

If s1 s2 string at the end of the string in the machine sorting sequence, the function returns a positive number equal returns zero, otherwise it is negative.

char  *strcmp  (const char* s1, const char*  s2,  size_t  n)

N characters before comparison only, if at the end of the string s1 s2 string sorted sequence in the machine, the function returns a positive number equal returns zero, otherwise it is negative.

char  *strchr  (const char* s,  int  c)

If s is included in the character string c, the function returns the string in position c s character first appears, it returns a null pointer is found.

char  *strpbrk  (const char* s1, const char*  s2)

If s1 s2 contains any character string, the function returns a pointer to the first location pointer s1 string, returns a null pointer is found.

char  *strchr  (const char* s,  int  c)

S1 position c character string returns the last occurrence, returns a null pointer is found.

char  *strstr  (const char* s1, const char*  s2)

Position is returned s1 s2 first occurrence of the string, it returns a null pointer is found.

size_t  strlen(const  char  *s)

S The number of characters in the string, excluding the null character.

11.6 String Samples

11.6.2 Select sort method

Comparing each element of the first loop element for use, if the elements to be compared in front of the first element of the current, the switching both the end of the first loop element contains a pointer to the most machine-ordered sequence of characters exam. Then the outer loop is repeated for this action.

11.7 ctype.h string and string

11.8 Command line parameters

int main  (int  argc  , char  *argv[])

The first command line argc number of strings, argv parameter values

例:hello  resistance  is  futile

Then, argc to 4 argv [] are sequentially stored, hello resistance is futile

11.9 string into digital

Included in the stdlib

atoi () into alphanumeric integers,

the atof () string into a double

atol () converted to a long string type

strtol () is converted to long type

strtoul () is converted to an unsigned long

strtod () is converted to double.

strol () and stroul () can be specified binary conversion.

long  strtol(const  char *restrict  nptr  char **restrict  endptr,int  base)

nptr to be transformed string pointer, the pointer address is endptr is, the pointer is set to identify the address of the end of the input character number.

That is, when the input nptr 10, endptr point '\ 0'

When nptr input 10at, endptr point 'a'

11.13 Programming Exercises

1, designed to test a function and can be read n characters (including spaces, tabs and line feed) from the input, the result is stored in an array, the address of the array to pass parameter

#include<stdio.h>
#include<stdlib.h>
char *s_gets(char *st,int n);
int main(void)
{
    int n=0;
    puts("请输入字符数组大小");
    scanf("%d",&n);
    while (getchar()!='\n')
    continue;
    char st[n];
    s_gets(st,n);
    system("pause");
    return 0;
}
char *s_gets(char *st,int n)
{
    int i=0;
    puts("请输入字符");
    while (i<n)
    {
        *(st+i)=getchar();
        i++;
    }
    i=0;
    while (i<n)
    {   
        printf("%c",*(st+i));
        i++;
    }   
    puts("");
    return st;
}

 

2, modify and test the function of an exercise, so that the n characters may be, or the first space, tab, newline stop reading the input, by the first to be satisfied in the case that the read termination (You can not use scanf () function)

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
char *s_gets(char *st,int n);
int main(void)
{
    int n=0;
    puts("请输入字符数组大小");
    scanf("%d",&n);
    while (getchar()!='\n')
    continue;
    char st[n];
    s_gets(st,n);
    system("pause");
     Return  0 ; 
} 
char * s_gets ( char * ST, int n-) 
{ 
    int I = 0 ; 
    the puts ( " Please enter the characters " );
     the while (I < n-) 
    {
         * (ST + I) = getchar ();
         iF (isspace becomes (* (ST + I)))   / * use isspace becomes () determines whether the input is a space, tab, newline or * / 
        BREAK ; 
        I ++ ; 
    } 
    I = 0 ;
     the while (I < n-) 
    {    
        the printf ( '%c",*(st+i));
        i++;
    }   
    puts("");
    return st;
}

3, design and test a function, its function is to read the input line in the first word to the array, and discard the other characters in the line. Definition of a word is a string of characters which does not contain spaces, tabs, or new

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
void word(char *p);
int main(void)
{
    char a[81];
 
    puts("Input the string.");
    gets(a);
    word(a);
    puts(a);
    system("pause");
    return 0;
}
void word(char *p)
{
    int begin,end;
    for(begin=0 ; isspace (* (the p-+ the begin)); the begin ++) the Continue ; // To find the beginning of a word 
    for (End = the begin;! Isspace (* (the p-+ End)); End ++) the Continue ; // find the end of a word 
    * ( P + End) = ' \ 0 ' ;
     for (; * (P + the begin) =! ' \ 0 ' ; P ++) // change the sorting 
        * P = * (P + the begin);
     * P = ' \ 0 ' ; 
}

5, design and test a function, its function is to search for the string specified by the first parameter of the function, find the location where the first specified by the second argument of the character first appears. If found, it returns a pointer to the character pointer: If not found, returns null character (in this way and strchr () function is the same function). Tested in a full program of using the loop to provide input for this function.

#include<stdio.h>
#include<stdlib.h>
char *mystrchr(char *p,char ch);
int main(void)
{
    char a[81];
    char b;
    char *p;
    do{
    puts("Input a string:");
    gets(a);
    puts("Input the char you want to find in the string:");
    b=getchar();
    getchar();
    p=mystrchr(a,b);
    if(p)
    {
        puts("Find!");
        puts(p);
    }
    else puts("Can't find!");
    puts("Input any char except q to quit.");
    gets(a);
    }
    while(*a!='q');
 
    puts("Quit.");
    system("pause");
    return 0;
}
char *mystrchr(char *p,char ch)
{
    char *p_save=p;
    if(*p=='\0')
        return NULL;
    while(1)
    {
        if(*p==ch)
           {
               return p_save;
           }
    else
    {
        if(*++p=='\0')
            return NULL;
        p_save=p;
    }
    }
}

 

6, write a function is_within (). It accepts two parameters, a character string other pointer. If the function is a character in a string, it returns a non-zero value (true); if the character is not a string, returns a value of 0 (false). Tested in a full program of using the loop to provide input for this function.

#include <stdio.h> 
#include <stdlib.h>
 int is_within ( char * P, char CH);
 int main ( void ) 
{ 
    char CH;
     char P [ 88 ];
     int B;
     do 
    { 
        the puts ( " Enter string " ); 
        the gets (the p-); 
        the puts ( " characters enter to find " ); 
        CH = getchar ();
         the while (getchar ()! = ' \ the n- ' ) the Continue; 
        B = is_within (P, CH);
         IF (B) 
            the puts ( " query to the value " );
         the else 
            the puts ( " not queried value " );   
        the puts ( " End If, enter q, do not end enter any other value " ); 
        CH = getchar ();
         the while (getchar ()! = ' \ n- ' ) Continue ; 
    } the while (CH =! ' Q ' ); 
    

} 
int is_within ( char * P,char ch)
{
    while(*p!='\0')
    {
        if (*p==ch)  return 1;
        p++;
    }
    return 0;
}

16. Write a program whose function is to read input until it encounters the end of the file, and the file is displayed. It requires the program to identify and execute the following command line parameters:

-p display output as it

-u input to all uppercase

-l convert all input into lowercase

 

Guess you like

Origin www.cnblogs.com/suwencjp/p/12427603.html