Chapter X string
A string constant is enclosed by a pair of double quotes string sequence
String is actually composed of a number of significant digits, and the character '\ 0' end of the sequence of characters as a
C language string data type is not provided, so use the access string character array to achieve
Character array is an array consisting of characters, only if it is the last element '\ 0' indicates when the string
Marks the end of the string '\ 0' is also one byte of memory, but it is not included in the actual length of the string, only included in the length of the array
Correct wording:
char str[6] = {'H','e','l','l','o','\0'};
char str[] = {'H','e','l','l','o','\0'};
char str[] = {"hello"};
char str[] = "hello";
Compiler will determine the size of the array in accordance with the number of characters in the string
The number of the array size is the actual string of characters plus 1
Multiple strings need to be stored in a two-dimensional array of characters
The number of strings represents the length dimension of the first array to be stored can be omitted
However, the length of the second dimension can not be omitted
Character pointers: a pointer to the variable character data
As long as the address of the first character string assigned to the pointer, you can make a pointer to a character string
String constants is stored on behalf of itself first address its constant storage area, is a constant address
char *ptr = "Hello";
Equivalent to
Char * on;
ptr = "Hello"; / * constant stored in the storage area of the "Hello" assigned to the first address ptr, not be interpreted as a string assigned to ptr * /
Constant string storage area is read-only
The array can be modified string
char str[10] = "Hello";
Char * Ptr = Cycle;
Equivalent to
char str[10] = "Hello";
Char * Ptr;
ptr = str; / * equivalent to ptr = & str [0] * /
* Ptr = 'W'; / * equivalent to ptr [0] = 'W'; corresponds str [0] = 'W'; * /
Proper use character pointer, the string must be saved to clear the character pointer points to where and where
test
#include <stdio.h>
int main()
{
char str[10] = "Hello";
char *ptr;
ptr = str;
printf("%p\n",ptr);
printf("%c\n",ptr[0]); printf("%s\n",str); *ptr = 'W'; printf("%p\n",ptr); printf("%c\n",ptr[0]); printf("%s\n",str); }
// operating results
0060FF02
H
the Hello
0060FF02
W
Wello
How to access individual characters in a string:
- The subscript: str [i]
- Pointer: If the character pointer ptr points to the first address of the character array str, * (ptr + i) corresponds str [I]
- ++ ptr operation by moving the pointer ptr, so that a character string pointed to by ptr
- For the array name str, may not operate to point through a character string str ++, because the array name is a constant address whose value can not be changed
String input / output:
for(i = 0; i < 10; i++)//输入
{
scanf("%c", &str[i]);
}
for(i = 0; str[i]! = '\0'; i++)//输出
{
printf("%c",str[i]);
}
scanf ( "% s", str ); // Input printf ( "% s", str ); // Output
// L10-1
#include <stdio.h>
#define N 12 is
int main ()
{
char name [N];
the printf ( "the Enter your name:" );
Scanf ( "% S" , name); the printf ( "% S the Hello \! the n-" , name); scanf ("% S ", name); / * read input buffer of the last remaining go unread character * / printf (" the Hello% S \ the n-"! , name); 0 return ;}
// operating results
the Enter your name: dingdingdangdang
the Hello dingdingdangdang!
The Enter your name: dingding dangdang
the Hello dingding!
The Hello dangdang!
With% d% s input digital or input string, ignoring spaces, carriage returns, tabs, etc., or blank characters (data is used as separator)
When read these characters, the system considers the end of the reading, and therefore a function scanf () can not be entered by the operator s format string with spaces
gets()
gets () at the end of line end of the string, while the carriage is read from the input buffer to go, but not as part of the string, and scanf () does not take the reading carriage, carriage remains in the input buffer
// L10-2
#include <stdio.h>
#define N 12
int main()
{
char name[N];
printf("Enter your name:");
gets(name);
printf("Hello %s!\n",name);
return 0;
}
// operating results
the Enter your name: dingding dangdang
the Hello dingding dangdang!
puts()
The puts address of the function () for the parameters given in parentheses from the start, the storage unit sequentially outputs the character
When encountering the first '\ 0' output end, and automatically outputs a newline
Convenient function puts () output string introduction, the only downside is not the same as add some additional character information in the output line function like printf () and controls the output format
Standard input gets () and the puts () is the C language / output functions
// L10-2
#include <stdio.h>
#define N 12 is
int main ()
{
char name [N];
the printf ( "the Enter your name:" );
fgets (name, the sizeof (name), stdin); / * limit input string does not exceed the size of the array length * / the printf ( "% S the Hello \ n-!" , name); return 0 ;}
// operating results
the Enter your name: dingding dangdang
the Hello dingding DA!
Function gets () does not limit the length of the input string, it is easy to cause a buffer overflow
Function scanf () also have this problem
fgets(name, sizeof(name), stdin);
The length of a line can be read from the stdin are led to the address name character string to the sizeof (name) of the storage area
Since this limits the length of the input string statement can not exceed the size of the array, so the extra characters entered by the user are discarded
// L10-3
#include <stdio.h>
#define N 12 is
int main ()
{
char name [N];
char STR [] = "\" the Hello \ ", to the I Said"; // \ "is an escape character, the representative double quotes
the printf ( "the Enter your name:" );
fgets (name, the sizeof ; (name), stdin) ( "\ n-% S% S." the printf , STR, name); return 0 ;}
//运行结果
Enter your name:dingding dangdang
"Hello", I said to dingding da.
:( string processing functions required at the beginning of the program header <string.h> be included in the source file)
strlen(str) | Seeking string length |
strcpy(str1,str2) | Copies the string str2 in str1 to an array of characters |
strcmp(str1,str2) | Compare strings str1 str2 and size of the two string from left to right according to the size of the ASCII value of the character-by-character comparison, or until a different character encounters '\ 0' until the |
strcat(str1,str2) | Connection string, add the string to the end of the string str2 str1 the character array, the character array str1 end of the string is a first character string str2 the cover, the connection string stored in the character array str1 returns the character array str1 after, the first address of the function call |
strncpy(str1,str2,n) | "N family" |
strncmp(str1,str2,n) | "N family" |
strncat(str1,str2,n) | "N family" |
// L10-4
#include <stdio.h>
#include <string.h>
#define MAX_LEN 10 / * maximum length of the string * /
#define N 150 / * number string * /
void SortString (STR char [] [MAX_LEN], int n-);
int main ()
{
int I, n-; char name [N] [MAX_LEN]; / * define a two-dimensional array of characters * / the printf ( "How MANY Countries?" ); Scanf ( "% D", & n- ); getchar (); / * read the input buffer walking carriage return * / / * the preceding scanf () leave a character in a buffer while reading the input '\ n' so that if this is not added a getchar () to take away the carriage return, then gets () will not wait type the characters from the keyboard, but will directly take away this "useless" carriage return, resulting in incorrect reading * / printf ( " Their names INPUT: \ n-" ); for (I = 0; I <n-; I ++ ) {the gets (name [I]);/ * Input string of n * / } SortString (name, n); / * String sorted lexicographically * /the printf ( "the Sorted Results: \ n" ); for (I = 0; I <n; I ++ ) {the puts (name [I]); / * outputting sorted n string * / } return 0 ;} / * function: realized exchange lexicographically sorted string * / void SortString (STR char [] [MAX_LEN], int n-) {int I, J; char TEMP [MAX_LEN]; for (I = 0; I <n- -1; I ++ ) {for (J = I +. 1; J <n-; J ++ ) {IF (strcmp (STR [J], STR [I]) <0 ) {strcpy (TEMP, STR [I]); / / assignment of the single character assignment operator can be used, but is not available for assignment operator assignment string // string assignment function can only be used strcpy () strcpy (STR [I], STR [J]); strcpy (str [j], temp );}}}}
//运行结果
How many countries?5
Input their names:
America
England
Australia
Sweden
Finland
Sorted results:
America
Australia
England
Finland
Sweden
Because the character array pointer and can access the character string C
Therefore, when the transfer function string, character array may be used as a function of parameters, characters may be used as a pointer to the function parameters
// L10-5
#include <stdio.h>
#define N 80
void MyStrcpy (dstStr char [], char srcstr []);
int main ()
{
char A [N], B [N];
the printf ( "String the Input A:" ) ; the gets (a); / * input string * / MyStrcpy (b, a); / * array of a character string is copied into b * / the printf ( "copy of the iS:" ); the puts (b) ; / * copy output string * / return 0 ;} / * function: copy implemented string * / void MyStrcpy a character array as a function of parameters (dstStr char [], char srcstr []) {int I = 0 ; / * initializes array subscript 0 * / while / * if the current character is not extracted marks the end of the string * / (srcstr [I] = '\ 0'!) {dstStr [I] = srcstr [I]; / * copy the characters * / I ++; / * mobile subscript * / } dstStr [I] = '\ 0'; / * end of the string, add the string dstStr end flag * / }
//运行结果
Input a string:Hello China
The copy is:Hello China
or
/ * Function: a character pointer as a function of parameters, and copy the string * /
void MyStrcpy (dstStr char *, char * srcstr)
{
the while (! * Srcstr = '\ 0') / * if the current character is not referred srcstr end of string flag * /
{
* dstStr = * srcstr; / * copy the characters * /
srcstr ++; / * make the next srcstr points to a character * / dstStr ++; / * make the next dstStr points to a memory unit * / } * dstStr = '\ 0 '; / * end of the string in the string is added dstStr end flag * / }
// L10-6
#include <stdio.h>
unsigned int MyStrlen (const char STR []);
int main ()
{
char A [80 ]; the printf ( "String the Input A:" ); the gets (A); the printf ( "of The length of iS string the: U% \ n-" , MyStrlen (a)); return 0 ;} / * function: a character array as a function of the parameters, calculate the length of the string * / unsigned int MyStrlen (const char STR []) {int I; unsigned int len = 0; / * counter is set to 0 * / for (I = 0; STR [I] = '\ 0';! I ++ ) {len ++; / * The cyclic statistics do not include '\ 0' including the number of characters * / } return len; / * return the actual number of characters * / }
//运行结果
Input a string:Hello China
The length of the string is: 11
In order to prevent accidental modification argument in the called function, the type of the const can be added in front of the corresponding parameter
If attempts to modify the value of this parameter in the body of the function, a compile error
function
char *strcpy(char *str1,const char *str2);
char *strcat(char *str1,const char *str2);
The return value is a character pointer str1, that the first address memory space to store the string str1
The purpose of this design is to increase the use of flexibility
Function between handshaking (exchange of information) is obtained by the function parameters and return values to achieve
Returns a string from the function pointer:
Returns a pointer to a function when defining need to add a number in front of the function name *
char * f (); defines a function f, the function return value is a character pointer
char (* f) (); F defines a function pointer, the function pointer to no parameter, the return value is a character
// L10-7
#include <stdio.h>
#define N 80
char * MyStrcat (dstStr char *, char * srcstr);
int main ()
{
char First [2 * N]; / * this array should be large enough to store the connection string * /
char SECOND [N];
the printf ( "The First the Input string:" ); the gets (First); the printf ( "The SECOND the Input string:" ); the gets (SECOND); the printf ( "Result of The IS:% S \ n-" , MyStrcat (First, SECOND)); return 0 ;} / * function: string srcstr dstStr connected to the string of * / char * MyStrcat (dstStr char *, char * srcstr) {char * pStr = dstStr; / * save string dstStr first address * / / * pointer to the end of the string dstStr * / the while (! * dstStr = '\ 0' ) {dstStr ++;} / * Copy the string srcstr to the string dstStr of * / for (; * srcstr = '\ 0';! DstStr ++, srcstr ++ ) {* dstStr = * srcstr;} * dstStr = '\ 0'; / * added after the end of the string is connected to the end of string flag * / return pStr; / * string dstStr first address after the return connection * / }
//运行结果
Input the first string:Hello
Input the second string:China
The result is: HelloChina
const type qualifier:
If you only want to be transferred data to the internal functions, which are not modified in the desired function
In this case, in order to prevent data from being inadvertently modified, so that the function function more clearly
Can be defined using the parameters const
(1) const before the type keyword
int a,b;
const int *p = &a;
p is a pointer variable, can point to a constant integer (Integer Constant)
* P is a constant, and p is not
* P is read-only, can not be modified in the program
Value of the pointer variable p can be modified
Variable p is pointing to a legitimate assignment is also
(2) const keyword in front of and behind the type of variable name *
int const *p = &a;
p is a pointer variable, can point to a constant integer (Constant Integer)
* P is a constant, and p is not
The first case is equivalent to
Front (3) const keyword * behind on type, variable name
int *const p = &a;
p is a pointer variable, integer data may point to a (Integer)
p is a constant, rather than * p
p is read-only, can not be modified in the program, i.e., it can not point to other variables
But it points to the value of a variable can be modified
(4) placed in front of a type of the keyword const, const placed between the other type of the keyword and the variable names *
const int *const p = &a;
p is a pointer variable, can point to a constant integer (Integer Constant)
* p and p are constants are read-only
Character handling functions:
int isdigit(int c) | If the number returned is true |
int isalpha(int c) | If the letter is returned true |
isalnum int (int c) | If it returns true numbers or letters |
int islower(int c) | If it returns true lowercase letters |
int issupper(int c) | Returns true if capital letters |
int tolower(int c) | If uppercase letters are converted to lowercase return |
int toupper(int c) | If the conversion is lowercase to uppercase return |
int isspace(int c) | If the character is blank (newline \ n-, space character, feed character \ F, carriage return \ R & lt, horizontal tab \ T, vertical tab \ V) returns true |
int iscntrl(int c) | If a control character (horizontal tab \ t, vertical tab \ v, feed character \ f, the alarm bell symbol \ a, backspace \ b, carriage return \ r, newline \ n) Returns true |
isprint you (you c) | If including spaces printable character ($, #, (,), [,], {,},;,:,%) returns true |
int isgraph(int c) | If space is in addition to the printable character returns true |
// L10-8
#include <stdio.h>
#define N 80
int main ()
{
char STR [N];
int I, Letter = 0, 0 = digit for, Space = 0, Others = 0 ;
the printf ( "String the Input A:" ) ; the gets (STR); for (I = 0; STR [I] = '\ 0';! I ++ ) { IF (STR [I]> = 'A' && STR [I] <= 'Z' || STR [I]> = 'A' && STR [I] <= 'the Z' ) Letter ++; / * statistics English characters * / else if (str [i ]> = '0' && str [i] <= ' . 9 ' ) digit for ++; / * statistics character * / the else IF (STR [I] ==' ' ) space ++; / * space statistics * / the else others ++; / * another character count * / } the printf ( "English character:% d \ n", letter); printf("digit character: %d\n", digit); printf("space: %d\n", space); printf("other character: %d\n", others); return 0; }
// L10-8
#include <stdio.h>
#include <ctype.h>
#define N 80
int main ()
{
char STR [N];
int I, Letter = 0, 0 = digit for, Space = 0, Others = 0 ; the printf ( "the Input A String:" ); the gets (STR); for (I = 0; STR [I] = '\ 0'; I ++! ) {IF (the isalpha (STR [I])) Letter ++; / * statistics English characters * / IF the else (isdigit (str [i])) digit ++; / * statistics character * / IF the else (isspace (str [i])) space ++; / * statistics spaces (in fact, also contains other whitespace characters) * / the else others ++; / * statistics other characters * / } printf ( "English character:% d \ the n-" , Letter); printf ( "character digit:% d \ the n-" , digit); printf ( "Space:% D \ n-" , Space);printf("other character: %d\n", others); return 0; }
//运行结果
Input a string:abcd 12345 (*)
English character: 4
digit character: 5
space: 2
other character: 3
// L10-9
#include <stdio.h>
#include <ctype.h>
#define N 80
int main ()
{
char name [N];
int I; the printf ( "the Input A name:" ); the gets (name); / * input and last name * / I = 0 ; (! the isalpha (name [I])) the while / * skip all spaces, until the case of the letter * / {I ++ ;} name [I] = toupper (name [I]); / * the first initial uppercase * / while / * skip all letters up until the case space * / (isspace becomes (name [I])!) {I ++ ;} the while (! the isalpha (name [I])) / * skip all spaces, until the letter case * / {I ++ ;} name [I] = toupper (name [I]); / * the first letter of the last name in uppercase * / the printf ( "the Formatted the name:% S \ n-" , name); return 0 ;}
// operating results
the Input A name: john smith
the Formatted the Name: John Smith
To convert the string of numerical values:
C language string conversion functions provided by the numeric string may be converted to integer or floating point type value
Using these functions, the header file must be included in the beginning of the program <stblib.h>
double atof(const chat *nPtr) | Converting the string pointed to nPtr double precision floating point |
int atoi(const char *nPtr) | The nPtr point convert integer string |
long atol(const char *nPtr) | The string pointed nPtr converted to a long integer |
// L10-10
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char STR [] = { "123.5" };
int intNum; Long longNum; Double DoubleNum; intNum = atoi (STR); / * String convert integer * / longNum = atol (STR); / * string is converted to a long integer * / DoubleNum = the atof (STR); / * string into double precision real number * / the printf ( "intNum % D = \ n-" , intNum); the printf ("% LD longNum = \ n-" , longNum); the printf ("% DoubleNum = F \ n-" , DoubleNum); return 0 ;}
// Run Results
intNum = 123
longNum = 123
DoubleNum = 123.500000