Dadas dos cadenas str1 y str2, nuestra tarea es concatenar estas dos cadenas. Hay varias formas de concatenar dos cadenas en lenguaje C:
- Sin usar la función strcat()
- Usando el método estándar
- Usando la función
- Usando recursividad
- Usando la función strcat()
1. Concatenar dos cadenas sin usar la función strcat()
A. Usando el método estándar
Input: str1 = 'hello', str2 = 'world' Output: helloworld Input: str1 = 'Geeks', str2 = 'World' Output: GeeksWorld>
Enfoque: uso del operador '+'
C++
#include> #include> using> namespace> std;> int> main() {> >string str1 =>'Geeks'>;> >string str2 =>'ForGeeks'>;> >string result = str1 + str2;> >cout << result << endl;> >return> 0;> }> |
>
>Producción
GeeksForGeeks>
Enfoque: uso de la función de agregar.
C++
#include> using> namespace> std;> int> main() {> >string str1 =>'hello'>;> >string str2 =>'world'>;> >cout<<>'The Resultant String Is :'>< cout< return 0; }> |
>
>Producción
The Resultant String Is : helloworld>
Análisis de complejidad:
Complejidad del tiempo:O(1).
Espacio Auxiliar: O(1).
Acercarse:
- Consigue que las dos cadenas se concatenen
- Declarar nuevas cadenas para almacenar la cadena concatenada
- Inserte la primera cadena en la nueva cadena.
- Inserte la segunda cadena en la nueva cadena.
- Imprime la cadena concatenada
A continuación se muestra la implementación del enfoque anterior:
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> |
>
>Producción
First string: Geeks Second string: World Concatenated string: GeeksWorld>
Complejidad del tiempo: O(m+n)
Espacio auxiliar: O(1)
B. Uso de la función
Acercarse:
- La función principal llamará a la función concatenate_string() para concatenar dos cadenas.
- La función obtendrá la longitud de la cadena s con la ayuda de strlen.
- Ahora agregaremos el carácter de la cadena s1 en s[i+j]. Este paso se repetirá hasta que no haya ningún carácter disponible en s1. Estamos agregando caracteres de la cadena s1 a s desde el final de s.
- Después del bucle for, concatenaremos la cadena s.
- Por último, la función principal imprimirá la cadena que está concatenada.
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;> }> |
>
>
Producción:
Enter the first string: Geeks Enter the second string: forGeeks Concatenated String is: 'techcodeview.com'>
Complejidad del tiempo: O(n+m), donde n es el tamaño de la cadena 1 y m es el tamaño de la cadena 2 respectivamente.
Espacio Auxiliar: O(1)
C. Usando recursividad
Acercarse:
- La función concatenate_string() obtendrá las cadenas s y s1.
- si no hay elementos presentes en s1, asigne a s1 un carácter nulo ( ).
- de lo contrario, si hay elementos presentes, agregaremos el elemento de la cadena s1 al final de la cadena s y aumentaremos el valor de i en 1.
- La función concatenate_string se llamará a sí misma pasando las cadenas modificadas s, s1 como argumentos. Esta función se llamará a sí misma de forma recursiva hasta que no haya elementos disponibles en 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;> }> |
>
>
Producción:
Enter the first string: Geeks Enter the second string: forGeeks Concatenated String is: 'techcodeview.com'>
Complejidad del tiempo: O(n+m), donde n es el tamaño de la cadena 1 y m es el tamaño de la cadena 2 respectivamente.
Espacio Auxiliar: O(1)
2. Usando la función strcat()
La función strcat() en C agrega la copia de la cadena de origen al destino con un carácter nulo al final de la cadena. Viene bajo el archivo de encabezado string.h en 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++
escribe json en el archivo python
#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)> |
>
>Producción
Final string is: techcodeview.com>
Complejidad del tiempo: O(n+m), donde n es el tamaño de la cadena 1 y m es el tamaño de la cadena 2 respectivamente.
Espacio Auxiliar: O(1)