Join Strings Function | C Programming Example

Portfolio Courses
23 Jan 202215:28

Summary

TLDRВ этом видео рассматривается создание функции объединения строк в языке C, аналогичной функции join в Python. Автор объясняет, как динамически выделять память для новой строки, вычислять её длину и объединять строки с разделителем, используя библиотеки string.h и stdlib.h. Пример демонстрирует, как строки объединяются с помощью функции strcopy и strconcat, при этом добавляются разделители. Видео также объясняет, как работать с динамически выделенной памятью для строк, и как правильно освобождать память по завершении программы.

Takeaways

  • 😀 В видео рассказывается о создании функции объединения строк в языке C, аналогичного функции join в Python.
  • 🔧 Для реализации функции используются библиотеки string.h и stdlib.h для работы со строками и динамического выделения памяти.
  • 📝 Создается двухмерный массив символов для хранения строк и строка-разделитель.
  • 💡 Функция join принимает массив строк, их количество и строку-разделитель, возвращая указатель на динамически созданную строку.
  • 🔄 Производится вычисление общей длины новой строки, учитывая количество и длину всех строк и разделителей.
  • 🚫 Реализована обработка ошибок, например, если количество строк равно нулю, функция возвращает NULL.
  • 🛠 Используются функции strcopy и strcat из библиотеки string.h для копирования и объединения строк.
  • 🔄 Создается версия функции join, принимающая динамически выделенный массив указателей на строки.
  • 📊 Демонстрируется тестирование функции с использованием статических и динамически выделенных строк.
  • 🗑️ В конце видео предлагается освободить выделенную память для соблюдения хороших практик программирования.

Q & A

  • Что делает функция join в C, описанная в видео?

    -Функция join в C объединяет массив строк, разделяя их заданным разделителем, аналогично функции join в Python.

  • Какие библиотеки включаются для реализации функции join в C?

    -Для реализации функции join в C включаются библиотеки string.h и stdlib.h.

  • Чему равна длина строки, которая будет создана функцией join, если используется разделитель из трех символов и три строки?

    -Длина новой строки будет равна длине разделителя, умноженной на количество строк минус один, плюс суммарная длина всех строк плюс один символ для null-терминатора.

  • Как определяется общий размер новой строки, создаваемой функцией join?

    -Общий размер новой строки определяется как длина разделителя, умноженная на количество строк минус один, плюс суммарная длина всех исходных строк плюс один символ для null-терминатора.

  • Какие функции из библиотеки string.h используются для создания новой строки?

    -Для создания новой строки используются функции strlen, strcpy и strcat из библиотеки string.h.

  • Чем отличается join2 от первоначальной функции join?

    -Функция join2 принимает массив указателей на динамически выделенные строки вместо 2D массива символов.

  • Почему использование 2D массива символов может быть неэффективным?

    -Использование 2D массива символов может быть неэффективным, так как все строки могут иметь выделенное пространство больше, чем необходимо, даже если сами строки короче.

  • Как проверяется, что функция join получает корректный массив строк?

    -Функция проверяет, что количество строк больше нуля, иначе возвращает NULL.

  • Какой символ используется для завершения строк в C?

    -В C все строки завершаются специальным символом null-терминатора '\0'.

  • После использования функций malloc и strcpy, зачем необходимо освобождать выделенную память?

    -Освобождение выделенной памяти после использования необходимо для предотвращения утечек памяти и более эффективного использования системных ресурсов.

Outlines

00:00

💻 Создание функции объединения строк в C

В этом видео мы создадим функцию объединения строк в языке программирования C, аналогичную функции join в Python. Функция будет объединять массив строк, разделенных заданной строкой-разделителем. Для реализации этой функции включаются библиотеки string.h и stdlib.h для работы со строками и динамического выделения памяти. Создается двухмерный массив символов для хранения строк и строка-разделитель. Функция join принимает массив строк, их количество и строку-разделитель, вычисляет общую длину новой строки с учетом разделителей и завершающего символа null, выделяет память для этой строки и использует функции копирования и объединения строк для создания результата, который затем возвращается.

05:02

🔍 Подробности реализации функции join в C

Второй параграф продолжает рассматривать процесс реализации функции join. Описывается процесс вычисления длины новой строки, учитывая количество символов в разделителях и оригинальных строках. Также рассматривается необходимость учета символа null-терминатора. Далее производится динамическое выделение памяти для новой строки с использованием функции malloc. После этого строится сама строка с помощью функций strcpy и strcat из библиотеки string.h, которые копируют и объединяют строки соответственно. Показывается, как вызывается функция join и как она тестируется с выводом результата на экран.

10:05

🔧 Создание улучшенной версии функции join с динамическим массивом строк

Третий параграф вводит улучшенную версию функции join, которая работает с динамическим массивом указателей на строки, выделенными в куче. Объясняется, что предыдущая версия функции join имела ограничение по максимальной длине строк, что могло приводить к неэффективному использованию памяти. Новая версия функции join2 принимает массив указателей на строки, выделенных в куче, и работает аналогично предыдущей, но без ограничений по максимальной длине. Показывается процесс создания динамического массива строк, вызова функции join2 и вывода результата.

15:05

🏁 Заключение и ресурсы для изучения C

В заключении видео автор подводит итоги и напоминает о важности освобождения выделенной памяти для предотвращения утечек. Также предлагает посетить ресурсы, такие как portfoliocourses.com, для получения дополнительных знаний и развития навыков в программировании на C, включая создание портфолио для усиления резюме.

Mindmap

Keywords

💡строки

Строки в контексте видео являются последовательностями символов, используемыми для хранения и передачи текста. В видео рассматривается функция объединения строк в C, которая аналогична функции join в Python. Примеры строк в скрипте включают 'abc', '0-9' и 'wxyz', которые объединяются с помощью разделителя.

💡разделитель

Разделитель - это символ или последовательность символов, используемая для разделения элементов в строке. В видео используется три '@' символа в качестве разделителя для объединения строк. Это важно для понимания, как строки соединяются и как они структурируются в конечном результате.

💡динамическая аллокация памяти

Динамическая аллокация памяти в C означает, что память выделяется в куче во время выполнения программы. В видео это делается с помощью функции malloc для создания нового строки, которая будет содержать объединенные исходные строки и разделители.

💡strlen

Функция strlen из библиотеки string.h используется для определения длины строки. В видео ее применение показывает, как рассчитывается общий размер новой строки, учитывая количество символов в разделителях и исходных строках.

💡строковые функции

Строковые функции в C предоставляют различные операции над строками, такие как копирование и конкатенация. В видео используются функции strcpy и strcat для создания новой строки из исходных строк и разделителей.

💡массивы

Массивы в C используются для хранения коллекций данных. В видео создается двумерный массив символов для хранения исходных строк и одномерный массив указателей для хранения динамичеки выделенных строк.

💡null-терминатор

Null-терминатор - это специальный символ (нулевой байт), обозначающий конец строки в C. В видео упоминается, что при расчете размера новой строки необходимо учитывать null-терминатор для корректного завершения строки.

💡malloc

Функция malloc используется для динамического выделения памяти в C. В видео она применяется для создания новой строки, которая будет содержать результат объединения исходных строк и разделителей.

💡free

Функция free используется в C для освобождения памяти, выделенной с помощью malloc. В видео упоминается важность освобождения памяти после использования, чтобы предотвратить утечки памяти.

💡портфельный курс

Портфельный курс в контексте видео означает набор учебных программ, направленных на развитие навыков программирования и создания портфеля проектов, которые могут впечатлить работодателей. Это указание на то, что видео может быть частью более широкого курса по программированию на C.

Highlights

Creating a string join function in C similar to Python's join function.

Including the string.h library for string copy and concatenation functions.

Including the stdlib.h library for dynamic memory allocation.

Defining a 2D array of characters to store strings.

Initializing the 2D character array with string data.

Defining a separator string for joining the elements.

Defining the join function to return a dynamically allocated string.

Error handling for cases where the string count is less than or equal to zero.

Calculating the length of the new string including separators.

Looping through the array to calculate the total length of the original strings.

Accounting for the null terminator in the new string length.

Dynamically allocating space for the new string based on the calculated length.

Copying the first string into the new string.

Concatenating the separator and subsequent strings to build the final string.

Returning the pointer to the newly created string.

Testing the join function with a sample set of strings and a separator.

Creating a second version of the join function to handle dynamically allocated strings.

Allocating and initializing a dynamically allocated array of pointers to strings.

Freeing the dynamically allocated memory to avoid memory leaks.

Transcripts

play00:00

in this video we're going to create a

play00:02

string join function in c

play00:04

that's going to be very much like

play00:05

python's join function

play00:07

so for example if we have strings like

play00:09

this abc

play00:11

the number 0 to 9 and wxyz

play00:14

as well as a separator string in this

play00:16

case three act characters

play00:18

our join function is going to join

play00:20

together

play00:21

those strings

play00:22

separated by

play00:24

the separator string like this

play00:26

so let's actually implement this now in

play00:28

c

play00:29

the first thing we'll do is include a

play00:30

couple libraries to help us

play00:32

we're going to include the string.h

play00:34

library

play00:35

because this library has helpful

play00:36

functions like a string copy function as

play00:39

well as a string concatenation function

play00:40

that we're going to use in our solution

play00:43

we'll also include the stdlib.h library

play00:46

because we're going to dynamically

play00:47

allocate space for the new string that

play00:49

we're going to create

play00:51

next we'll actually create a 2d array of

play00:53

characters to store these strings

play00:55

themselves so we'll say car strings and

play00:57

i'll say here open bracket

play01:00

and i'll actually define a max string

play01:02

length so i'll say here max

play01:04

and then up here i'll say

play01:06

number to find

play01:07

max20

play01:10

and save time i'm just going to paste in

play01:13

the code to initialize our 2d character

play01:16

array

play01:17

with the string data

play01:19

now next we're also going to need a

play01:20

separator string so i'll say here car

play01:24

separator is equal to

play01:27

and i'll just put a space here

play01:29

because we basically have a sentence

play01:31

here

play01:32

and i want to separate each one of the

play01:33

words in the sentence with a space

play01:36

using this join function

play01:38

so next we'll actually define the

play01:39

function itself

play01:41

so here i'll say car star join

play01:44

car

play01:45

strings

play01:47

and it's going to be a 2d array

play01:49

with max length strings

play01:52

and then we'll say int count

play01:54

and car star

play01:56

separator

play01:57

so this function here is going to return

play01:59

a pointer to the dynamically allocated

play02:02

string that we're going to create

play02:04

the first argument is going to be the

play02:06

strings themselves they're going to be

play02:07

stored in a 2d character array

play02:10

count is going to be the number of

play02:12

strings in that 2d array

play02:15

and then separator is going to be

play02:17

separated string

play02:19

so we'll copy and paste this

play02:21

and they'll provide a definition of the

play02:22

function down here

play02:25

so the way that we're going to solve

play02:26

this problem is we're first going to

play02:28

figure out how many characters are going

play02:31

to be in the new string

play02:33

and then we're going to dynamically

play02:34

allocate enough space on the heap to

play02:37

store a string with that number of

play02:38

characters

play02:40

then we're going to use the string copy

play02:42

and string concatenation operations that

play02:45

we get with the string.h library to

play02:47

actually copy in the strings and the

play02:50

separator to build the new string

play02:53

so the first thing we'll do is a little

play02:54

bit of error handling here i'm going to

play02:56

say if the count is less than or equal

play02:59

to 0

play03:01

then return null

play03:02

because we can't actually build a new

play03:04

string

play03:06

if the count of strings in the 2d array

play03:08

is 0 or somehow less than 0.

play03:11

next we'll start figuring out how long

play03:13

our new string is going to be

play03:15

the first thing we'll do is say int new

play03:18

length

play03:19

is equal to

play03:20

the string length

play03:22

of the separator string

play03:24

times count

play03:26

minus one

play03:28

so we're going to figure out how long

play03:30

the new string is going to be

play03:33

using this new length variable

play03:35

and the first thing we're going to do is

play03:36

figure out how many characters in that

play03:38

new string are going to be for the

play03:40

separator

play03:41

so to figure that out we call the string

play03:43

length function

play03:44

strlen that's provided by the string.h

play03:47

library

play03:48

it's going to return the length of the

play03:50

separator string

play03:52

then we're going to multiply that by

play03:54

count minus 1.

play03:56

so the reason why we do that

play03:57

is that's the number of separator

play03:59

strings that are going to appear in the

play04:01

new string

play04:02

so for example when we have three

play04:04

strings

play04:06

there's going to be two separator

play04:07

strings

play04:09

because there's going to be a separator

play04:10

string after every string

play04:12

except for the last one that last string

play04:14

does not have a separator string after

play04:16

it so that's why we have count minus one

play04:19

and we multiply it by the number of

play04:21

characters in the separator string

play04:23

because that will give us the total

play04:24

number of characters necessary in the

play04:26

new string to store the separator string

play04:28

characters

play04:29

next we've got to figure out how many

play04:31

characters are going to be in the new

play04:32

string for storing

play04:34

all of the original strings

play04:36

so to do that we're going to loop

play04:38

through

play04:39

this

play04:40

array here of those strings and we'll

play04:42

add the string length of each one of

play04:44

them

play04:44

to new length so here we'll say 4

play04:48

int i is equal to 0

play04:50

i is less than count i plus plus

play04:54

and we'll say new length plus equals

play04:58

and we'll add the string length

play05:01

of the next string so here we've got a

play05:03

loop with a counter variable i that's

play05:05

going from zero up until the number of

play05:07

strings in our array there and we're

play05:10

adding the length of each string

play05:12

to new length

play05:14

so we'd go through these strings one at

play05:15

a time find their length and add that

play05:18

length to new length

play05:20

so now new length is going to actually

play05:22

have the number of characters that we're

play05:24

actually going to be storing in the new

play05:26

string

play05:27

but there's one more character we got to

play05:29

worry about and that's the null

play05:30

terminator so remember that all strings

play05:33

in c are terminated with the special

play05:35

null terminator character so if we say 0

play05:38

that's what it looks like and we have to

play05:40

account for that character

play05:41

so far we haven't really done that

play05:43

because string length doesn't include

play05:45

the null terminator of a string so if we

play05:47

said string length of separator here

play05:50

it would be 3 in the case of these three

play05:52

at characters here

play05:54

so we're gonna do is just add one to new

play05:57

length just to account for that

play05:58

character

play05:59

and now we can actually dynamically

play06:00

allocate space for this new string

play06:02

because we know exactly how long it's

play06:04

gonna be we'll say car star

play06:06

new string is equal to

play06:08

malloc

play06:09

sizeof car

play06:11

times

play06:12

new length

play06:14

so malloc is going to return a pointer

play06:17

that we're going to store into new

play06:18

string it's going to be a pointer to a

play06:21

block of dynamically allocated space on

play06:23

the heap

play06:24

large enough to store the string that

play06:26

we're going to create

play06:28

now the size that's going to allocate is

play06:30

going to be size of character

play06:32

times new length so in other words we

play06:35

want enough space to store this many

play06:37

characters

play06:39

next we'll do is actually build the new

play06:41

string itself

play06:43

so to do that we're going to use the

play06:44

string copy and string concatenation

play06:47

functions that come with the string.h

play06:49

library

play06:50

so the first thing we'll do is copy in

play06:53

the first string

play06:55

into new string

play06:56

so we'll say

play06:57

str cpy

play07:00

new string

play07:01

and strings

play07:02

zero

play07:04

so what we're going to do is take the

play07:06

first string in our array

play07:08

and copy it into new string

play07:11

so at this point if we're working with

play07:13

this data here

play07:15

new string

play07:16

would look like this

play07:18

we'd have abc in it

play07:20

because string copy is going to store

play07:23

this string

play07:25

into new string and we'd have abc in

play07:27

this case now next what we need to do

play07:30

with all these subsequent strings

play07:33

is concatenate on

play07:34

the separator string

play07:36

followed by

play07:38

the next string

play07:40

if we just kept doing that

play07:42

like we put at at followed by

play07:45

the next string

play07:47

followed by the separator

play07:50

followed by the next string

play07:52

that would do it we would have built our

play07:54

string

play07:55

so let's actually do that

play07:57

what we'll do is use the string

play07:58

concatenation function from the

play08:00

string.each library

play08:02

to concatenate on exactly those strings

play08:04

so we'll say here 4

play08:06

into i is equal to 1

play08:08

i is less than count

play08:10

i plus plus

play08:13

and then we'll say str cat which is the

play08:16

string concatenation function

play08:18

and we'll say new string

play08:20

separator

play08:23

so this will concatenate on the

play08:25

separator string

play08:27

onto the end of new string

play08:29

and then after that

play08:30

we'll concatenate on the next string

play08:32

in our array of strings so we'll say str

play08:35

cat

play08:36

new string

play08:38

strings

play08:39

at i

play08:42

so this time we have i the counter

play08:44

variable going from one up until the

play08:46

number of strings in our array

play08:49

and we're just concatenating on the

play08:51

string

play08:52

after the separator for each string in

play08:54

the array

play08:55

and the way the str cap function works

play08:57

is it basically just takes this string

play08:58

here and puts it on to the end of the

play09:00

string here

play09:01

so that's really it now we can just

play09:03

return

play09:04

the pointer to our new string

play09:07

let's actually test this function out

play09:08

now

play09:10

we'll go up here and we'll call the

play09:12

function we'll say car star

play09:14

new string is equal to

play09:17

join

play09:18

strings

play09:20

we've got nine strings here so we'll say

play09:22

nine for the count

play09:24

and then we'll give the separator string

play09:25

as well

play09:27

and then we'll print out the string we

play09:29

get back so we'll say printf

play09:30

percent s slash n

play09:32

and we'll output new string

play09:34

so if we save and run this we should get

play09:36

in a gentle way you can shake the world

play09:39

with each word separated by space

play09:41

and that is exactly what we get there

play09:44

so there's one thing about this function

play09:46

that i'm not too happy with

play09:48

right now the way we've written the

play09:50

function it expects a 2d character array

play09:54

in each one of those strings is going to

play09:56

have some max length

play09:58

and this is just by virtue of the way

play10:00

that we pass

play10:01

2d arrays to functions in c so we don't

play10:04

necessarily like this because this means

play10:06

that our strings have a max length

play10:09

we could always increase that max length

play10:11

but it's also sort of memory inefficient

play10:14

because in this 2d character array

play10:16

all of the strings are going to have max

play10:19

number of characters allocated for them

play10:21

even if the strings themselves are much

play10:23

smaller than that

play10:25

so chances are if we're going to use a

play10:27

join function

play10:29

we might actually be dynamically

play10:30

allocating space for our strings on the

play10:32

heap anyways

play10:34

so we're going to create another version

play10:35

of this function

play10:37

that's going to accept a dynamically

play10:39

allocated array of pointers to

play10:41

dynamically allocated strings on the

play10:45

so we'll copy this

play10:47

paste it

play10:49

and we'll make a join two function and

play10:51

the join two function

play10:53

is gonna have this as its first argument

play10:55

car star star strings

play10:58

so it's gonna accept a dynamically

play11:00

allocated array of pointers to strings

play11:03

that have been cells been dynamically

play11:04

allocated on the heap as well

play11:07

so to create the join to function is not

play11:09

going to be too bad

play11:10

we'll actually just copy and paste join

play11:16

and we'll change that parameter

play11:18

we'll say car

play11:20

star star strings and we'll call it join

play11:22

two

play11:23

but other than that it's going to be the

play11:25

same because the string length functions

play11:28

the string concatenation functions and

play11:29

string copy functions these all work the

play11:32

same way

play11:33

whether the string is on the heap or on

play11:36

the stack

play11:37

so other than that the function will be

play11:39

the same

play11:41

so we'll test this function out now

play11:43

by creating a dynamically allocated

play11:45

array of pointers to strings that are

play11:47

going to be dynamically allocated as

play11:49

well

play11:49

so here i'll say car star star

play11:53

strings 2 is equal to malloc sizeof

play11:57

car star

play11:58

and we'll say times three

play12:02

so what we're going to do is dynamically

play12:04

allocate enough space

play12:06

to store three

play12:08

pointers to a character

play12:10

in other words three pointers two

play12:12

strings

play12:15

then we'll dynamically allocate space

play12:16

for each string so i'll say strings

play12:19

two

play12:21

at index zero which is our first pointer

play12:24

is equal to malloc

play12:26

sizeof

play12:28

car

play12:30

times

play12:32

4.

play12:33

so this is going to dynamically allocate

play12:35

enough space

play12:37

to store four

play12:38

characters

play12:40

and it's going to return a pointer to

play12:41

that that we're going to store into

play12:43

strings 2 at index 0.

play12:45

next we'll copy into that space as

play12:48

string so we'll say strcpy

play12:50

and we'll copy into

play12:53

this

play12:54

dynamically allocated block of space the

play12:56

string

play12:58

abc

play12:59

including the null terminator that's

play13:01

going to be four characters right

play13:02

because you got abc and then the null

play13:04

terminator as well

play13:06

we'll do the same for the next two

play13:07

strings so we'll say strings two

play13:10

at one is equal to

play13:12

malloc size of a character

play13:15

times eleven

play13:17

and this time we'll use string copy to

play13:19

copy in

play13:21

the string with the characters

play13:23

zero to nine

play13:26

and then we'll say strings two edit x2

play13:30

is equal to malloc and we'll allocate

play13:32

space for one more string size of car

play13:36

times five

play13:38

now we use string copy to copy in

play13:41

the string

play13:42

w x y z

play13:45

then we'll make our separator string so

play13:47

we'll say car separator

play13:49

2

play13:50

is equal to

play13:51

at

play13:54

and then we'll call the join 2 function

play13:55

so we'll say car star

play13:58

new string

play14:00

2

play14:00

is equal to join two

play14:02

with strings two there's three of those

play14:04

strings so we'll say account of three

play14:06

and we'll give separator two as an

play14:08

argument as well

play14:11

and then after run this we'll print out

play14:12

the string so we'll say printf

play14:15

percent s n and we'll say new string two

play14:19

and we'll save her on this

play14:22

and we get our original case there with

play14:24

abc

play14:25

the three ats

play14:27

zero to nine the three ads

play14:29

and wxyz

play14:30

so it doesn't matter too much because

play14:33

this program is going to end now

play14:35

but just to be completionist about it we

play14:38

should free the space that we've

play14:39

dynamically allocated

play14:41

so if we said here free new string

play14:45

free

play14:46

new string 2

play14:49

and then free

play14:51

strings to

play14:52

add index 0

play14:54

free

play14:55

strings 2

play14:57

index one

play14:58

free

play14:59

strings two added x2

play15:02

and then finally free

play15:04

strings two

play15:06

and we save and run this

play15:08

it won't affect our program but

play15:10

technically speaking

play15:11

just to kind of follow a good convention

play15:14

we'll free the space that we dynamically

play15:15

allocated as well so that's it that's

play15:18

how we can create a join function in c

play15:20

checkout portfolio courses.com where

play15:22

we'll help you build a portfolio that

play15:23

will impress employers including courses

play15:25

to help you develop c programming

play15:27

projects

Rate This

5.0 / 5 (0 votes)

Étiquettes Connexes
C-программированиеФункция joinСтрокиСоединениеДинамический массивМаллокСтатическое и динамическая памятьСтроки в CПример кодаУчебный материалПорфолио курсы
Besoin d'un résumé en anglais ?