Join Strings Function | C Programming Example
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
💻 Создание функции объединения строк в C
В этом видео мы создадим функцию объединения строк в языке программирования C, аналогичную функции join в Python. Функция будет объединять массив строк, разделенных заданной строкой-разделителем. Для реализации этой функции включаются библиотеки string.h и stdlib.h для работы со строками и динамического выделения памяти. Создается двухмерный массив символов для хранения строк и строка-разделитель. Функция join принимает массив строк, их количество и строку-разделитель, вычисляет общую длину новой строки с учетом разделителей и завершающего символа null, выделяет память для этой строки и использует функции копирования и объединения строк для создания результата, который затем возвращается.
🔍 Подробности реализации функции join в C
Второй параграф продолжает рассматривать процесс реализации функции join. Описывается процесс вычисления длины новой строки, учитывая количество символов в разделителях и оригинальных строках. Также рассматривается необходимость учета символа null-терминатора. Далее производится динамическое выделение памяти для новой строки с использованием функции malloc. После этого строится сама строка с помощью функций strcpy и strcat из библиотеки string.h, которые копируют и объединяют строки соответственно. Показывается, как вызывается функция join и как она тестируется с выводом результата на экран.
🔧 Создание улучшенной версии функции join с динамическим массивом строк
Третий параграф вводит улучшенную версию функции join, которая работает с динамическим массивом указателей на строки, выделенными в куче. Объясняется, что предыдущая версия функции join имела ограничение по максимальной длине строк, что могло приводить к неэффективному использованию памяти. Новая версия функции join2 принимает массив указателей на строки, выделенных в куче, и работает аналогично предыдущей, но без ограничений по максимальной длине. Показывается процесс создания динамического массива строк, вызова функции join2 и вывода результата.
🏁 Заключение и ресурсы для изучения C
В заключении видео автор подводит итоги и напоминает о важности освобождения выделенной памяти для предотвращения утечек. Также предлагает посетить ресурсы, такие как portfoliocourses.com, для получения дополнительных знаний и развития навыков в программировании на C, включая создание портфолио для усиления резюме.
Mindmap
Keywords
💡строки
💡разделитель
💡динамическая аллокация памяти
💡strlen
💡строковые функции
💡массивы
💡null-терминатор
💡malloc
💡free
💡портфельный курс
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
in this video we're going to create a
string join function in c
that's going to be very much like
python's join function
so for example if we have strings like
this abc
the number 0 to 9 and wxyz
as well as a separator string in this
case three act characters
our join function is going to join
together
those strings
separated by
the separator string like this
so let's actually implement this now in
c
the first thing we'll do is include a
couple libraries to help us
we're going to include the string.h
library
because this library has helpful
functions like a string copy function as
well as a string concatenation function
that we're going to use in our solution
we'll also include the stdlib.h library
because we're going to dynamically
allocate space for the new string that
we're going to create
next we'll actually create a 2d array of
characters to store these strings
themselves so we'll say car strings and
i'll say here open bracket
and i'll actually define a max string
length so i'll say here max
and then up here i'll say
number to find
max20
and save time i'm just going to paste in
the code to initialize our 2d character
array
with the string data
now next we're also going to need a
separator string so i'll say here car
separator is equal to
and i'll just put a space here
because we basically have a sentence
here
and i want to separate each one of the
words in the sentence with a space
using this join function
so next we'll actually define the
function itself
so here i'll say car star join
car
strings
and it's going to be a 2d array
with max length strings
and then we'll say int count
and car star
separator
so this function here is going to return
a pointer to the dynamically allocated
string that we're going to create
the first argument is going to be the
strings themselves they're going to be
stored in a 2d character array
count is going to be the number of
strings in that 2d array
and then separator is going to be
separated string
so we'll copy and paste this
and they'll provide a definition of the
function down here
so the way that we're going to solve
this problem is we're first going to
figure out how many characters are going
to be in the new string
and then we're going to dynamically
allocate enough space on the heap to
store a string with that number of
characters
then we're going to use the string copy
and string concatenation operations that
we get with the string.h library to
actually copy in the strings and the
separator to build the new string
so the first thing we'll do is a little
bit of error handling here i'm going to
say if the count is less than or equal
to 0
then return null
because we can't actually build a new
string
if the count of strings in the 2d array
is 0 or somehow less than 0.
next we'll start figuring out how long
our new string is going to be
the first thing we'll do is say int new
length
is equal to
the string length
of the separator string
times count
minus one
so we're going to figure out how long
the new string is going to be
using this new length variable
and the first thing we're going to do is
figure out how many characters in that
new string are going to be for the
separator
so to figure that out we call the string
length function
strlen that's provided by the string.h
library
it's going to return the length of the
separator string
then we're going to multiply that by
count minus 1.
so the reason why we do that
is that's the number of separator
strings that are going to appear in the
new string
so for example when we have three
strings
there's going to be two separator
strings
because there's going to be a separator
string after every string
except for the last one that last string
does not have a separator string after
it so that's why we have count minus one
and we multiply it by the number of
characters in the separator string
because that will give us the total
number of characters necessary in the
new string to store the separator string
characters
next we've got to figure out how many
characters are going to be in the new
string for storing
all of the original strings
so to do that we're going to loop
through
this
array here of those strings and we'll
add the string length of each one of
them
to new length so here we'll say 4
int i is equal to 0
i is less than count i plus plus
and we'll say new length plus equals
and we'll add the string length
of the next string so here we've got a
loop with a counter variable i that's
going from zero up until the number of
strings in our array there and we're
adding the length of each string
to new length
so we'd go through these strings one at
a time find their length and add that
length to new length
so now new length is going to actually
have the number of characters that we're
actually going to be storing in the new
string
but there's one more character we got to
worry about and that's the null
terminator so remember that all strings
in c are terminated with the special
null terminator character so if we say 0
that's what it looks like and we have to
account for that character
so far we haven't really done that
because string length doesn't include
the null terminator of a string so if we
said string length of separator here
it would be 3 in the case of these three
at characters here
so we're gonna do is just add one to new
length just to account for that
character
and now we can actually dynamically
allocate space for this new string
because we know exactly how long it's
gonna be we'll say car star
new string is equal to
malloc
sizeof car
times
new length
so malloc is going to return a pointer
that we're going to store into new
string it's going to be a pointer to a
block of dynamically allocated space on
the heap
large enough to store the string that
we're going to create
now the size that's going to allocate is
going to be size of character
times new length so in other words we
want enough space to store this many
characters
next we'll do is actually build the new
string itself
so to do that we're going to use the
string copy and string concatenation
functions that come with the string.h
library
so the first thing we'll do is copy in
the first string
into new string
so we'll say
str cpy
new string
and strings
zero
so what we're going to do is take the
first string in our array
and copy it into new string
so at this point if we're working with
this data here
new string
would look like this
we'd have abc in it
because string copy is going to store
this string
into new string and we'd have abc in
this case now next what we need to do
with all these subsequent strings
is concatenate on
the separator string
followed by
the next string
if we just kept doing that
like we put at at followed by
the next string
followed by the separator
followed by the next string
that would do it we would have built our
string
so let's actually do that
what we'll do is use the string
concatenation function from the
string.each library
to concatenate on exactly those strings
so we'll say here 4
into i is equal to 1
i is less than count
i plus plus
and then we'll say str cat which is the
string concatenation function
and we'll say new string
separator
so this will concatenate on the
separator string
onto the end of new string
and then after that
we'll concatenate on the next string
in our array of strings so we'll say str
cat
new string
strings
at i
so this time we have i the counter
variable going from one up until the
number of strings in our array
and we're just concatenating on the
string
after the separator for each string in
the array
and the way the str cap function works
is it basically just takes this string
here and puts it on to the end of the
string here
so that's really it now we can just
return
the pointer to our new string
let's actually test this function out
now
we'll go up here and we'll call the
function we'll say car star
new string is equal to
join
strings
we've got nine strings here so we'll say
nine for the count
and then we'll give the separator string
as well
and then we'll print out the string we
get back so we'll say printf
percent s slash n
and we'll output new string
so if we save and run this we should get
in a gentle way you can shake the world
with each word separated by space
and that is exactly what we get there
so there's one thing about this function
that i'm not too happy with
right now the way we've written the
function it expects a 2d character array
in each one of those strings is going to
have some max length
and this is just by virtue of the way
that we pass
2d arrays to functions in c so we don't
necessarily like this because this means
that our strings have a max length
we could always increase that max length
but it's also sort of memory inefficient
because in this 2d character array
all of the strings are going to have max
number of characters allocated for them
even if the strings themselves are much
smaller than that
so chances are if we're going to use a
join function
we might actually be dynamically
allocating space for our strings on the
heap anyways
so we're going to create another version
of this function
that's going to accept a dynamically
allocated array of pointers to
dynamically allocated strings on the
so we'll copy this
paste it
and we'll make a join two function and
the join two function
is gonna have this as its first argument
car star star strings
so it's gonna accept a dynamically
allocated array of pointers to strings
that have been cells been dynamically
allocated on the heap as well
so to create the join to function is not
going to be too bad
we'll actually just copy and paste join
and we'll change that parameter
we'll say car
star star strings and we'll call it join
two
but other than that it's going to be the
same because the string length functions
the string concatenation functions and
string copy functions these all work the
same way
whether the string is on the heap or on
the stack
so other than that the function will be
the same
so we'll test this function out now
by creating a dynamically allocated
array of pointers to strings that are
going to be dynamically allocated as
well
so here i'll say car star star
strings 2 is equal to malloc sizeof
car star
and we'll say times three
so what we're going to do is dynamically
allocate enough space
to store three
pointers to a character
in other words three pointers two
strings
then we'll dynamically allocate space
for each string so i'll say strings
two
at index zero which is our first pointer
is equal to malloc
sizeof
car
times
4.
so this is going to dynamically allocate
enough space
to store four
characters
and it's going to return a pointer to
that that we're going to store into
strings 2 at index 0.
next we'll copy into that space as
string so we'll say strcpy
and we'll copy into
this
dynamically allocated block of space the
string
abc
including the null terminator that's
going to be four characters right
because you got abc and then the null
terminator as well
we'll do the same for the next two
strings so we'll say strings two
at one is equal to
malloc size of a character
times eleven
and this time we'll use string copy to
copy in
the string with the characters
zero to nine
and then we'll say strings two edit x2
is equal to malloc and we'll allocate
space for one more string size of car
times five
now we use string copy to copy in
the string
w x y z
then we'll make our separator string so
we'll say car separator
2
is equal to
at
and then we'll call the join 2 function
so we'll say car star
new string
2
is equal to join two
with strings two there's three of those
strings so we'll say account of three
and we'll give separator two as an
argument as well
and then after run this we'll print out
the string so we'll say printf
percent s n and we'll say new string two
and we'll save her on this
and we get our original case there with
abc
the three ats
zero to nine the three ads
and wxyz
so it doesn't matter too much because
this program is going to end now
but just to be completionist about it we
should free the space that we've
dynamically allocated
so if we said here free new string
free
new string 2
and then free
strings to
add index 0
free
strings 2
index one
free
strings two added x2
and then finally free
strings two
and we save and run this
it won't affect our program but
technically speaking
just to kind of follow a good convention
we'll free the space that we dynamically
allocated as well so that's it that's
how we can create a join function in c
checkout portfolio courses.com where
we'll help you build a portfolio that
will impress employers including courses
to help you develop c programming
projects
関連動画をさらに表示
#11. Спецсимволы, экранирование символов, raw-строки | Python для начинающих
Глава 1 Базовый Синтаксис ; День 36 ; 36.2
FastAPI - Как использовать Depends #14
ИЗУЧИТЕ ГЛАВНУЮ НЕЙРОСЕТЬ МИРА от Б до Ю
ЭКОНОМИЯ ВРЕМЕНИ И ДЕНЕГ ПРИ ВЫБОРЕ НЕЙРОСЕТИ (МОДЕЛИ ТИПА LLM)
GPT-4o - анализ графиков, рынка и стратегий на Python / OpenAI GPT-4o Python Tutorial @AVKlimov
5.0 / 5 (0 votes)