# 15.	Строки. Строковой и символьный литералы. Представление в памяти.

### Строки. Строковой и символьный литералы. <a href="#stroki.-strokovoi-i-simvolnyi-literaly." id="stroki.-strokovoi-i-simvolnyi-literaly."></a>

В языке C (Си) нет отдельного типа для строк, но в программе строки могут определяться как **массивы символов** (массив элементов типа char) или **строковые константы**.

Как и массив, это непрерывный участок памяти, объединенный единым именем.

**Строковый литерал " "** – это последовательность символов в двойных кавычках (строковая константа) или массив символов, заканчивающийся терминальным нулем \0.

**Символьный литерал ' '** – один символ в одинарных кавычках.

​

<img src="https://3074527236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FOlTieA4l7aQXw27w94AS%2Fuploads%2FtypCdoqzG3KxuXuC3LCN%2Fimage.png?alt=media&#x26;token=46e8e590-0b1b-4062-80f8-67c13b41172d" alt="" width="100%">

​

### Выделение памяти и инициализация <a href="#vydelenie-pamyati-i-inicializaciya" id="vydelenie-pamyati-i-inicializaciya"></a>

**Статическое выделение:**

`char string[41];` - создан массив из 41 символа типа char

`char string[] = "Горные вершины спят во тьме ночной.";`

**Динамическое выделение:**

`char *str = “Hello”`

### Основные функции и их реализация: <a href="#osnovnye-funkcii-i-ikh-realizaciya" id="osnovnye-funkcii-i-ikh-realizaciya"></a>

На экзамене обязательно указать реализацию strcpy, strlen +strcat

`strtok` - aнaлог функции `split` в `Python`

```c
unsigned int strlen (const char *s) // вычисляет длину строки
{
    unsigned int i;
    for (i = 0; *(s + i) != 0; i++);
    return i;
}    
 
char* strcpy(char *s1, const char* s2) // копирует строку
{
    unsigned int i;
    for (i = 0; (*(s1 + i) = *(s2 + i)); i++);
    return s1;
}
 
char *strcat(char *s1, const char *s2) // "склеивает" строки
{
    char *p;
    unsigned int i;
    for (p = s1; *p; p++);
    for (i = 0; p[i] = s2[i]; i++);
    return p;
}
 
int strcmp(const char* s1, const char *s2) // сравнивает строки. 0 - строки одинаковы,\
 1 - в первой строке первый отличающийся символ больше, чем во второй,\
 -1 - в первой строке первый отличающийся символ меньше, чем во второй.
{
    unsigned int i;
    for (i = 0; *(s1 + i) && (*(s1 + i) == *(s2 + i)); i++);
    return *(s1 + i) - *(s2 - i);
}
 
const char* strchr(const char* s, char ch) // возвращает указатель на первый символ ch в строке
{
    const char *p;
    for (p = s; *p && *p != ch; p++);
    return p;
}
 
char* strstr(const char* s, const char* sub_s) // возвращает указатель на начало подстроки
{
    int key = 0;
    char* p;
    for (p = s; !key && *p;) {
        unsigned i;
        for (i = 0; *(sub_s + i) && (*(p + i) == *(sub_s + i)); i++);
        if (!*(sub_s + i))
            key = 1;
        else
            p++;
    }
    return key ? p : NULL;
}
 
char* strpbrk(const char* s, const char* sym) // возвращает указатель на любой символ из sym,\
 который первый встретился
{
    int key = 0;
    char* p;  
    for (p = s; !key && *p;) {
        unsigned i;
        for (i = 0; *(sym + i) && (*p != *(sym + i)); i++);
        if (*(sym + i))
            key = 1;
        else
            p++;
    }
    return key ? p : NULL;
 }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://op-al.gitbook.io/s-30-voprosy-i-dop.-voprosy/15.-stroki.-strokovoi-i-simvolnyi-literaly.-predstavlenie-v-pamyati..md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
