logo

Конкатенація двох рядків у C

Дано два рядки str1 і str2, наше завдання полягає в тому, щоб об’єднати ці два рядки. Існує кілька способів об’єднати два рядки мовою C:

  • Без використання функції strcat().
    • Стандартним методом
    • Використання функції
    • Використання рекурсії
  • Використання функції strcat().

1. Конкатенація двох рядків без використання функції strcat().

A. Використання стандартного методу

 Input: str1 = 'hello', str2 = 'world' Output: helloworld Input: str1 = 'Geeks', str2 = 'World' Output: GeeksWorld>

Підхід: використання оператора «+».



C++






#include> #include> using> namespace> std;> int> main() {> >string str1 =>'Geeks'>;> >string str2 =>'ForGeeks'>;> >string result = str1 + str2;> >cout << result << endl;> >return> 0;> }>



>

>

Вихід

GeeksForGeeks>

Підхід: використання функції додавання.

C++




#include> using> namespace> std;> int> main() {> >string str1 =>'hello'>;> >string str2 =>'world'>;> >cout<<>'The Resultant String Is :'>< cout< return 0; }>

>

>

Вихід

The Resultant String Is : helloworld>

Аналіз складності:

Часова складність: O(1).

Допоміжний простір: O(1).

Підхід:

  • Отримайте два рядки для об’єднання
  • Оголошення нових рядків для зберігання об’єднаного рядка
  • Вставте перший рядок у новий рядок
  • Вставте другий рядок у новий рядок
  • Надрукуйте об’єднаний рядок

Нижче наведено реалізацію вищезазначеного підходу:

C




// C Program to concatenate two> // strings without using strcat> #include> > int> main()> {> > >// Get the two Strings to be concatenated> >char> str1[100] =>'Geeks'>, str2[100] =>'World'>;> > >// Declare a new Strings> >// to store the concatenated String> >char> str3[100];> > >int> i = 0, j = 0;> > >printf>(>' First string: %s'>, str1);> >printf>(>' Second string: %s'>, str2);> > >// Insert the first string> >// in the new string> >while> (str1[i] !=>' '>) {> >str3[j] = str1[i];> >i++;> >j++;> >}> > >// Insert the second string> >// in the new string> >i = 0;> >while> (str2[i] !=>' '>) {> >str3[j] = str2[i];> >i++;> >j++;> >}> >str3[j] =>' '>;> > >// Print the concatenated string> >printf>(>' Concatenated string: %s'>, str3);> > >return> 0;> }>

>

>

C++




// C++ Program to concatenate two> // strings without using strcat> #include> using> namespace> std;> > int> main()> {> > >// Get the two Strings to be concatenated> >char> str1[100] =>'Geeks'>, str2[100] =>'World'>;> > >// Declare a new Strings> >// to store the concatenated String> >char> str3[100];> > >int> i = 0, j = 0;> > >cout <<>' First string: '><< str1;> >cout <<>' Second string: '><< str2;> > >// Insert the first string> >// in the new string> >while> (str1[i] !=>' '>) {> >str3[j] = str1[i];> >i++;> >j++;> >}> > >// Insert the second string> >// in the new string> >i = 0;> >while> (str2[i] !=>' '>) {> >str3[j] = str2[i];> >i++;> >j++;> >}> >str3[j] =>' '>;> > >// Print the concatenated string> >cout <<>' Concatenated string: '><< str3;> > >return> 0;> }> // this code is contributed by shivanisingh>

>

>

Вихід

First string: Geeks Second string: World Concatenated string: GeeksWorld>

Часова складність: O(m+n)
Допоміжне приміщення: О(1)

B. Використання функції

Підхід:

  • Функція main викличе функцію concatenate_string() для об’єднання двох рядків.
  • Функція отримає довжину рядка s за допомогою strlen.
  • Тепер ми додамо символ рядка s1 до s[i+j]. Цей крок повторюватиметься, доки в s1 не буде жодного символу. Ми додаємо символи рядка s1 до s з кінця s.
  • Після циклу for ми будемо об’єднувати рядок s.
  • Нарешті основна функція надрукує об’єднаний рядок.

C




// C program to concatenating two> // strings using function> #include> #include> void> concatenate_string(>char>* s,>char>* s1)> {> >int> i;> >int> j =>strlen>(s);> >for> (i = 0; s1[i] !=>' '>; i++) {> >s[i + j] = s1[i];> >}> >s[i + j] =>' '>;> >return>;> }> int> main()> {> >char> s[5000], s1[5000];> >printf>(>'Enter the first string: '>);> >gets>(s);> >printf>(>'Enter the second string: '>);> >gets>(s1);> >// function concatenate_string> >// called and s and s1 are> >// passed> >concatenate_string(s, s1);> >printf>(>'Concatenated String is: '%s' '>, s);> >return> 0;> }>

>

>

Вихід:

Enter the first string: Geeks Enter the second string: forGeeks Concatenated String is: 'techcodeview.com'>

Часова складність: O(n+m), де n — розмір рядка 1, а m — розмір рядка 2 відповідно.
Допоміжний простір: О(1)

C. Використання рекурсії

Підхід:

  • Функція concatenate_string() отримає рядки s і s1.
  • якщо в s1 немає елементів, тоді призначте s1 нульовий символ ( ).
  • інакше, якщо елементи присутні, ми додамо елемент рядка s1 у кінець рядка s і збільшимо значення i на 1.
  • Функція concatenate_string викличе сама себе, передаючи модифіковані рядки s, s1 як аргументи. Ця функція рекурсивно викликає себе, доки в s1 не буде доступних елементів.

C




// C program to concatenate two> // strings with the help of> // recursion> #include> #include> void> concatenate_string(>char>* s,>char>* s1)> {> >static> int> i = 0;> >static> int> j =>strlen>(s);> >if> (!s1[i]) {> >s1[i] =>' '>;> >}> >else> {> >s[i + j] = s1[i];> >i++;> >concatenate_string(s, s1);> >}> }> int> main()> {> >char> s[5] =>'Geeks'>, s1[8] = 'forGeeks;> >// function concatenate_string> >// called and s1 and s2 are> >// passed> >concatenate_string(s, s1);> >printf>(>' Concatenated String is: '%s' '>, s);> >return> 0;> }>

>

>

Вихід:

Enter the first string: Geeks Enter the second string: forGeeks Concatenated String is: 'techcodeview.com'>

Часова складність: O(n+m), де n — розмір рядка 1, а m — розмір рядка 2 відповідно.
Допоміжний простір: О(1)

2. Використання функції strcat().

Функція strcat() у C додає копію вихідного рядка до місця призначення з нульовим символом у кінці рядка. Він міститься у файлі заголовків string.h у C.

C




// C program to concatenate two> // strings using strcat function> #include> #include> int> main()> {> >char> s[] =>'Geeks'>;> >char> s1[] =>'forGeeks'>;> >// concatenating the string> >strcat>(s, s1);> >printf>(>'Final string is: %s '>, s);> >return> 0;> }>

>

>

C++


java містить підрядок



#include> #include> using> namespace> std;> int> main()> {> >char> s[] =>'Geeks'>;> >char> s1[] =>'forGeeks'>;> >// concatenating the string> >strcat>(s, s1);> >cout <<>'Final string is: '> << s;> >return> 0;> }> // This code is contributed by Akshay> // Tripathi(akshaytripathi630)>

>

>

Вихід

Final string is: techcodeview.com>

Часова складність: O(n+m), де n — розмір рядка 1, а m — розмір рядка 2 відповідно.
Допоміжний простір: О(1)