c language string details

1. String literal.

"Candy \nIs dandy \nBut liquor \nIs quicker."

It is called a string literal in C++. You can embed the transfer sequence within the string, such as'\n'

Be careful to embed the octal and hex transfer sequences in the string. The octal transfer sequence starts with /, the hexadecimal transfer sequence starts with /x (x must be lowercase) , and the octal transfer sequence is three digits (must be within the range of 0-7) End afterwards or end with the first non-octal number (the number is greater than or equal to 8 and ends).

There is no restriction after hexadecimal /x, and ends with the first non-hexadecimal digit (greater than f). Note that hexadecimal numbers can be capitalized (obtained from the results of the compiler). For example, look at the following code:

#include <stdio.h>
int main()
{
if(('\xAA') ==  ('\xaa'))
        printf("equal");
else 
        printf("not equal.");
    return 0;
}

The result of the operation is:

equal

2. Continue the string literal.

(1) Method 1: Use \

For example "i am a student \

   and you are a teacher. "

Features: The first line ends with \ (not included), and the second line starts at the beginning of the line.

(2) Method 2: When two or more strings are adjacent, the C language will automatically merge the strings. Use this rule to write like this

"i am a student  "

" and you are a teacher. "

Finally, the compiler will merge the strings itself. "i am a student and you are a teacher. "

3. Storage of string literals. C language stores string literals as character arrays. When the c language encounters a string of length n, it will allocate a memory space of length n+1 for the string literal, and add'\0' to the end. Note: Do not confuse'\0', '0' , and '' here. The code value of the null character is 0, and the code value of '0' (ASCII) is 48, and the code value of the space '' ASCll is 32. Remember, if the character array is initialized by default, it will be'\0'.

When the character array is initialized by default, each character is also assigned a value of'\0' instead of the space bar, and each digit of the arithmetic type array is initialized to 0.

The empty string is "", the empty string is stored as a single empty character,'\0'

The string literally is stored as an array, so the string literally will be treated as a pointer (the array name will be treated as a pointer). For example, printf("abcde"); then the string "abcde" will be passed to the printf function The address (that is, the pointer to the memory unit of the character a).

4. String literals will be treated as pointers.

E.g. "abc"

printf("abc"); Here, "abc" will be regarded as a pointer to the memory unit of letter a.

Both printf and scanf accept char * type as their first parameter.

5. Operation of string literals.

(1) The character string literal value cannot be changed. Look at the following code:

#include <stdio.h>
int main()
{
char *str = "abcde";
*str = 'a';
printf("%s",str);
   return 0;
}                                                                         
                

A runtime error occurred in the running result:

r@r:~/coml_/c/13/2$ gcc 3.c -o 123
r@r:~/coml_/c/13/2$ ./123
Segmentation fault (core dumped)
r@r:~/coml_/c/13/2$ 

Conclusion: The content of the string literal cannot be changed. But you can make the char * object point to another string, for example,

#include <stdio.h>
int main()
{
char *str = "abcde";
printf("%s\n",str);
//str 重新指向另一个字符串字面量
str = "efghikasdfasd fasdf asdf asdf asf";
printf("%s",str);
return 0;

The results are as follows:

abcde
efghikasdfasd fasdf asdf asdf asfr

Unexpected place: can exceed the length of the original string.

(2) In half of the cases, you can use string literals wherever char * is needed.

For example, char *p;

p = "abc"; This operation is not to copy the string, but to assign the address of the character a to p, that is, the assignment process of the pointer variable p, not the entire assignment process of the string.

(3) Pointers have subscript operations, and string literals also have

"abc"[1] refers to the character b

The following function converts integers into hexadecimal characters.

char number_to_hex(int n)
{
return "0123456789ABCDEF"
}                                                                         
  

(4) Note here hexadecimal and octal number and transfer sequence is not the same

          (a) The definition of hexadecimal number \x00 ( x is both uppercase and lowercase, the number part has no length requirement ), the definition of octal number, \012 (the beginning of the number 0 is an octal number, and the number after \0 has no length limit )

         (b) The hexadecimal escape sequence must start with \x ( x must be lowercase, and the following digits must be at most 2 digits from 0 to ff ), and the octal transfer sequence must begin with \ , and the following digits must be at most 3 digits . See the following figure. Review

6. String literals and character constants cannot be interchanged, see the following code:

#include <stdio.h>
int main()
{
printf("\n");
printf('\n');  //这里引发错误
    return 0;
}        

The compilation results of the gcc compiler are as follows:

r@r:~/coml_/c/13/2$ gcc 4.c -o 123
4.c: In function ‘main’:
4.c:5:8: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast [-Wint-conversion]
    5 | printf('\n');
      |        ^~~~
      |        |
      |        int
In file included from 4.c:1:
/usr/include/stdio.h:332:43: note: expected ‘const char * restrict’ but argument is of type ‘int’
  332 | extern int printf (const char *__restrict __format, ...);
      |                    ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~
4.c:5:1: warning: format not a string literal and no format arguments [-Wformat-security]
    5 | printf('\n');

7. String variables. Note that it must end with "\0", otherwise undefined behavior will occur when library functions call it.

#include <stdio.h>
#define STR_LEN 20
int main()
{
//方法1:直接定义成字符数组+初始化
char str[STR_LEN + 1] = "you are welcome.";
//方法2:直接定义为char * + 初始化
char * str1 = "you are welcome.";
//方法3:先定义一个字符数组,和一个char *,把char *对象指向一个char 数组
char str2[STR_LEN + 1],*str3;
str3 = str2;
//方法4:先定义一个char *,后来可以指向一个字符串字面值
char *ptr;
ptr = "you are welcome";
puts(ptr);
  return 0;
}

But if you want to use scanf to read char*, you must first open up enough space, that is, you must first declare the type as char [STR_LEN + 1], but not as the type char *.

char *p; //Only enough for pointer p to store a pointer space. Can not allocate space for the string. If you use p to read in, it will cause an error:

#include <stdio.h>
int main()
{
char *p;
scanf("%s",p);
printf("%s",p);
  return 0;
}

The results of the operation are as follows: after you have entered you aresdf as required, the output is indeed null

you arasdf
(null)

8. Initialize string variables

When the c language handles the array initialization formula, when the array initialization formula is shortened by the array itself, the remaining array elements will be initialized to 0 (the elements are int, float, double), and the char array follows the same rules. '\0' added.

No matter you assign a value to char * or char [] (the value type is a string literal), it will automatically be added with'\0' at the end

#include <stdio.h>
int main()
{
double d[12] = {0.0};
int i;
for(i = 0; i!= 12; ++i)
{
printf("%f\n",d[i]);
}
   return 0;
}
~   

The results are as follows:

0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000

9. Character array and character pointer

Similarities: wherever character arrays or character pointers are accepted, both can be used as actual parameters.

difference:

(1) The character array can modify the value of a character, but the character pointer cannot modify the string literal value.

(2) The name of the character array is the array name, and the character pointer is a variable, which can point to other strings during execution.

For example, char *p, where p is a pointer variable that points to a char object. The value of p can be changed, just that (the object pointed to by p cannot be changed, distinguish *p = ... (illegal), and p = ... (legal))

char *p;

p = "abcde";//Legal, here is the value of p changed. p is a variable, of course it can be changed.

*p = "efghi";//Illegal, if you want to change the string literal pointed to by p, an error will be reported.

 

10. Reading and writing of strings

(1) Read

Use scanf or fget();

Features: All blanks after the beginning will be ignored. For example, if you enter a bc def, the beginning blanks will be ignored. Finally, a will be read in, and the latter will be cached in the memory, waiting for subsequent reads.

(2) Write

                 printf("") will output strictly one by one until the first'\0' is encountered. If there is no'\0' at the end of the string, it will continue to write out until the first'\0' in the memory is encountered. 0'.

                puts(), will add a'\n' directly at the end of the line (auto wrap)

(3) The problems to be solved by writing the read string function are as follows

   (a) When to start reading (whether to ignore the initial blank character) (b) How to end'\n', the space is still a certain character, whether the end character should be written into the string (c) If the read string is too Long, then the extra characters are ignored directly, or left for the next input operation.

For example, if the newline character is not ignored, the first newline character ends, and the newline character does not exist in the string, then write as follows, the function read() in the code:

#include <stdio.h>
#define LEN 20
int read(char str[],int n);
void print(char str[],int n);
int main()
{
char array[LEN + 1] = {' '};
read(array,LEN);
print(array,LEN+1);
    return 0;
}
int read(char str[],int n)
{
char ch;
char *p = str;
int i = 0;
while((ch = getchar()) != '\n')
{
 if(i < n)
 { *p ++ = ch;
     i++;
  }
}
*p = '\0';
return i;

}
void print(char str[],int n)
{
int i = 0;
for(i = 0; i!= n; ++i)
  {
    printf("%c",str[i]);
  }
}

                   The function read() can also be simply written as follows:

int read(char str[],int n)
{int i = 0;
char ch;
  while((ch = getchar()) != '\n')
  {
  if(i < n)
      str[i ++] = ch;
  }
  str[i] = '\0';  //terminates string
  return i;       //number of characters stored
}

The scanf function and the gets function will automatically add a null character at the end. However, if you write your own function, you must add the null character yourself.

 

 

 

 

 

Guess you like

Origin blog.csdn.net/digitalkee/article/details/112757288