No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

String.h

9/12
Recursos

¿Cómo trabajar con strings en C?

Los strings son fundamentales en cualquier lenguaje de programación, y C no es la excepción. Este lenguaje ofrece poderosas herramientas para manipularlos mediante la biblioteca string.h. Aquí exploramos las funciones más esenciales y cómo aplicarlas de manera práctica.

¿Cómo puedes almacenar strings en un array?

Para trabajar con strings en C, es necesario almacenarlos en un array de caracteres (char array). Así, puedes preservar tus cadenas de caracteres de manera eficiente:

#include <stdio.h>
#include <string.h>

int main() {
    char string1[60]; // Declara un array de 60 caracteres
    printf("Escribe una frase: ");
    gets(string1); // Usa gets para obtener el string
    return 0;
}

¿Qué es y cómo usar la función strrev?

La función strrev es sumamente útil para invertir el sentido de una cadena de caracteres. Esto puede ser ilustrado usando un palíndromo:

strrev(string1); // Invierte el string almacenado en string1
printf("El string al revés es: %s\n", string1); // Imprime el string invertido

¿Cómo funciona la comparación con strcmp?

La función strcmp nos permite comparar dos strings y determinar si son iguales. Retorna 0 si las cadenas son idénticas y 1 si son diferentes:

char string2[60];
printf("Escribe otra frase para comparar: ");
gets(string2);

if (strcmp(string1, string2) == 0) {
    printf("Ingresaste dos strings idénticos\n");
} else {
    printf("Ingresaste dos cosas distintas\n");
}

¿De qué manera strcat permite concatenar strings?

Concatenar strings es una tarea común que strcat facilita al unir dos cadenas:

strcat(string1, string2); // Concatena string2 a string1
printf("Si las unimos, el resultado es: %s\n", string1);

Consejos prácticos para trabajar con funciones de strings

  1. Entender los argumentos: Muchas funciones de string.h requieren que pases los strings como argumentos.
  2. Tener en cuenta los caracteres especiales: Casos como mayúsculas y minúsculas pueden alterar el resultado de comparaciones.
  3. Experimenta y explora: Practica con diferentes funciones como strlen, strcpy, entre otras, para comprender su potencial.

Ánimos y sigue explorando: La cantidad de funciones que C ofrece para strings es vasta. Cada función añade una herramienta más a tu caja de herramientas de programación. Te animamos a seguir explorando, probando y ampliando tus conocimientos. ¡Nos vemos en la próxima clase!

Aportes 21

Preguntas 8

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Aparentemente la funcion strrev no se puede usar si usas linux. Segun lo que lei en este caso tendrias que definir tu funcion para reversar caracteres. El codigo se veria asi:

#include <stdio.h>
#include <string.h>

void reverse(char [], int, int);

int main()
{
    char string1[60]; //Cadena de caracteres de 60
    int size;

    printf("Escribe una frase genial: \n");
    
    gets(string1); // Este es especifico para strings
    size = strlen(string1);

    reverse(string1, 0, size - 1); // string reverse

    printf("El string al reves es: %s \n", string1);

    return 0;
}

void reverse(char str1[], int index, int size)
{
    char temp;

    temp = str1[index];
    str1[index] = str1[size - index];
    str1[size - index] = temp;

    if (index == size / 2)
    {
        return;
    }
    reverse(str1, index + 1, size);
}

Solo mencionar un pequeño aporte, si haces el prework antes de este curso o cualquier a de C, debes considerar que al abrir VSCode utilizas Ubuntu como shell y ello te dará errores cuando compiles con librerias math.h y string.h, te sugiero abrir VSCode desde el menu inicio (windows) para que funcione la extensión Compile Run y las librerias que habla el profesor Ricardo

Si tienes linux o el WSL en windows + librerias de C, puedes consultar la ayuda para ver más información de las funciones.
Ejemplo: man strcmp

STRCMP(3)                                                                            Linux Programmer's Manual                                                                            STRCMP(3)

NAME
       strcmp, strncmp - compare two strings

SYNOPSIS
       #include <string.h>

       int strcmp(const char *s1, const char *s2);

       int strncmp(const char *s1, const char *s2, size_t n);

DESCRIPTION
       The  strcmp()  function  compares the two strings s1 and s2.  It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be
       greater than s2.

       The strncmp() function is similar, except it compares only the first (at most) n bytes of s1 and s2.

RETURN VALUE
       The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match,  or
       be greater than s2.

ATTRIBUTES
       For an explanation of the terms used in this section, see attributes(7).

       ┌────────────────────┬───────────────┬─────────┐
       │Interface           │ Attribute     │ Value   │
       ├────────────────────┼───────────────┼─────────┤
       │strcmp(), strncmp() │ Thread safety │ MT-Safe │
       └────────────────────┴───────────────┴─────────┘
CONFORMING TO
       POSIX.1-2001, POSIX.1-2008, C89, C99, SVr4, 4.3BSD.

SEE ALSO
       bcmp(3), memcmp(3), strcasecmp(3), strcoll(3), string(3), strncasecmp(3), strverscmp(3), wcscmp(3), wcsncmp(3)

COLOPHON
       This  page  is  part  of  release 4.15 of the Linux man-pages project.  A description of the project, information about reporting bugs, and the latest version of this page, can be found at
       https://www.kernel.org/doc/man-pages/.

strrev no esta para el compilador gcc en Linux por lo tanto lo que encontre es que se tiene que hacer la función:

char *strrev(char *str){
    char c, *front, *back;

    if(!str || !*str)
        return str;
    for(front=str,back=str+strlen(str)-1;front < back;front++,back--){
        c=*front;*front=*back;*back=c;
    }
    return str;
}

Algo a tomar en cuenta, es que gets es peligroso y no se deberia de usar: https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used

Para los que tengan problema con GETS, FGETS, etc, Este video lo explica todo: https://youtu.be/Lksi1HEMZgY

En AWS Cloud9 no puedo usar gets() ahí debo usar fgets()

https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm

¿Alguien sabe cómo ponerle un espacio entre ambos strings comparados con strcat para que se vea mejor?

strcat(string1, string2);
//Espacio entre el string1 y string2 en el resultado printf.

Otras funciones de la libreria String
man string

STRING(3)                                                                            Linux Programmer's Manual                                                                            STRING(3)

NAME
       stpcpy,  strcat,  strchr,  strcmp,  strcoll, strcpy, strcspn, strdup, strfry, strlen, strncat, strncmp, strncpy, strpbrk, strrchr, strsep, strspn, strstr, strtok,
       strxfrm, - string operations

SYNOPSIS
       #include <string.h>

       char *stpcpy(char *dest, const char *src);
              Copy a string from src to dest, returning a pointer to the end of the resulting string at dest.

       char *strcat(char *dest, const char *src);
              Append the string src to the string dest, returning a pointer dest.

       char *strchr(const char *s, int c);
              Return a pointer to the first occurrence of the character c in the string s.

       int strcmp(const char *s1, const char *s2);
              Compare the strings s1 with s2.

       int strcoll(const char *s1, const char *s2);
              Compare the strings s1 with s2 using the current locale.

       char *strcpy(char *dest, const char *src);
              Copy the string src to dest, returning a pointer to the start of dest.

       size_t strcspn(const char *s, const char *reject);
              Calculate the length of the initial segment of the string s which does not contain any of bytes in the string reject,

       char *strdup(const char *s);
              Return a duplicate of the string s in memory allocated using malloc(3).


       char *strfry(char *string);
              Randomly swap the characters in string.

       size_t strlen(const char *s);
              Return the length of the string s.

       char *strncat(char *dest, const char *src, size_t n);
              Append at most n characters from the string src to the string dest, returning a pointer to dest.

       int strncmp(const char *s1, const char *s2, size_t n);
              Compare at most n bytes of the strings s1 and s2.

       char *strncpy(char *dest, const char *src, size_t n);
              Copy at most n bytes from string src to dest, returning a pointer to the start of dest.

       char *strpbrk(const char *s, const char *accept);
              Return a pointer to the first occurrence in the string s of one of the bytes in the string accept.

       char *strrchr(const char *s, int c);
              Return a pointer to the last occurrence of the character c in the string s.

       char *strsep(char **stringp, const char *delim);
              Extract the initial token in stringp that is delimited by one of the bytes in delim.

       size_t strspn(const char *s, const char *accept);
              Calculate the length of the starting segment in the string s that consists entirely of bytes in accept.

       char *strstr(const char *haystack, const char *needle);
              Find the first occurrence of the substring needle in the string haystack, returning a pointer to the found substring.

       char *strtok(char *s, const char *delim);
              Extract tokens from the string s that are delimited by one of the bytes in delim.

       size_t strxfrm(char *dest, const char *src, size_t n);
              Transforms src to the current locale and copies the first n characters to dest.

DESCRIPTION
       The string functions perform operations on null-terminated strings.  See the individual man pages for descriptions of each function.

SEE ALSO
       index(3), rindex(3), stpcpy(3), strcasecmp(3), strcat(3), strchr(3), strcmp(3), strcoll(3), strcpy(3), strcspn(3), strdup(3), strfry(3), strlen(3), strncasecmp(3), strncat(3),  strncmp(3),
       strncpy(3), strpbrk(3), strrchr(3), strsep(3), strspn(3), strstr(3), strtok(3), strxfrm(3)

COLOPHON
       This  page  is  part  of  release 4.15 of the Linux man-pages project.  A description of the project, information about reporting bugs, and the latest version of this page, can be found at
       https://www.kernel.org/doc/man-pages/.

                                                                                             2014-01-04                                                                                   STRING(3)
Hoy en día 2024 la funcion gets esta obsoleta, en su lugar se puede usar la funcion fgets que necesita 3 parametros. .
`#include <stdio.h>#include <string.h> ``//biblioteca string ` `int main(){    char string1[60];` `    printf("Escribe una frace\n");    gets(string1);`` //comandio exacto para adquirir datos de un string ` `    strrev(string1);`` // comando para convertir el string al reves ` `    printf("El string al reves es: %s\n", string1);` `    return 0;}`
Actualmente la fucnión gets está obsoleta por su seguridad y en muchos casos da errores al quere usarla, y para otros tipos de funciones que nos permiten captar arrays de caracteres son incompatibles, tuve que usar fgets `#include <stdio.h>` `#include <string.h>` `int main()` `{` ` char string1[10];` ` ` ` printf("Escribe una frase: \n");` ` fgets(string1, sizeof(string1), stdin);` ` ` ` // Remove the newline character at the end of the input` ` if (string1[strlen(string1) - 1] == '\n') {` ` string1[strlen(string1) - 1] = '\0';` ` }` ` ` ` int length = strlen(string1);` ` char reversed[length + 1]; // +1 for the null terminator` ` ` ` for (int i = 0; i < length; i++) {` ` reversed[i] = string1[length - i - 1];` ` }` ` reversed[length] = '\0'; // Null-terminate the reversed string` ` ` ` printf("El string al reves es: %s\n", reversed);` ` return 0;` `}`

Excelente

#include <stdio.h>
#include <string.h>

int main()
{
    char string1[60];
    printf("Escribe una Frase: \n");
    gets(string1);

    char string2[60];
    printf("Escribe otra Frase: \n");
    gets(string2);

    if(strcmp(string1, string2)==0)
    {
        printf("Ingresaste 2 strings identicos");
    }
    else
    {
        printf("Los strings son diferentes \n");
        printf("Ahora las uniremos \n");
        strcat(string1, string2);
        printf(string1);
    }
}

Holaaa, les doy mi explicacion de como solucionar el problema de gets, con fgets.

**MI SOLUCION ANTE EL PROBLEMA DEL GETS EN LINUX DE MANERA FACIL:**

COMO OBTENER VARIABLES DE UN USUARIO

La solucion utiliza el modulo fgets

```c
//Mi solucion ante el problema de gets en linux:

#include <string.h>
#include <stdio.h>

char* string1;
size_t size;
char string2[60];
char enter;

char*  strrev(char* str);
//fgets(variable en donde guardar, longitud, file_pointer(DONDE ESTA EL ARCHIVO, EN ESTE CASO STDIN QUE SIGNIFICA EL ARCHIVO ACTUAL))

int main()
{
	printf("Type a sentence: \n");
    fgets(string2, 60, stdin);
    
    printf("%s \n", string2);

	
//Si se siente araro el codigo,le abajo

	return 0;
}

Mi solucion ante el problema de gets en linux:
La solucion parte de usar el metodo fgets.

#include <string.h>
#include <stdio.h>

char * string1;
size_t size;
char string2[60];
char enter;

char *strrev(char * str);
//fgets(variable en donde guardar, longitud, file_pointer)

int main()
{
printf(“Type a sentence: \n”);
fgets(string2, 60, stdin);

printf("%s \n", string2);

/*printf("Y la reversa es: %c ", *strrev(string2)); */


return 0;

}

Código

#include <stdio.h>
#include <string.h>

char string1[60];
char string2[60];
char string3[60];

int main()
{
    printf("Escribe una frase para invertirla: ");
    gets(string1);//Obtiene la cadena del teclado y la asigna al arreglo de char pasado como parámetro
    strrev(string1);//Invierte el string
    printf("Frase invertida: %s", string1);

    printf("\nEscribe una frase\n");
    gets(string2);
    printf("Escribe otra frase para comparar o conctenar si no diferentes\n");
    gets(string3);

    if (strcmp(string2, string3) == 0) // Copara 2 strings
    { 
        printf("Son iguales\n");
    }
    else
    {
        strcat(string2, string3);//Concatena dos cadenas
        printf("Son diferentes, concatenadas resultan: %s\n", string2);
    }

    return 0;
}

gets no debería usarse, NUNCA. Pueden usar fgets, que es completamente seguro.

Por otro lado, también hay 2 bibliotecas importantes que son útiles para el manejo de cadenas de texto:
<wchar.h>
<stddef.h>

Si se han dado cuenta, al imprimir carácteres fuera del rango ASCII estándar (como la ñ y vocales acentuadas), con %s y%ls se ve el texto sin problema (asumiendo que el escaneo de entrada fue con eso mismo o con fgets) pero si intentan imprimir el carácter individualmente con %c, les arrojará mojibake. Para imprimir carácteres especiales hacen uso de cualquiera de estas 2 bibliotecas, configuran el locale y ya podrán mostrar estos carácteres uno por uno correctamente con %lc
Y para finalizar, si la consola se atasca, pueden usar freopen() para cambiar el flujo del stream ya que cada vez que se imprime o se lee texto wide con wprintf/wscanf este flujo es modificado y no vuelve automáticamente “a la normalidad”. A menos que usen un solo tipo de texto (char o widechar) a lo largo de todo el código, esto será necesario para desatascar la lectura y escritura de datos si mezclan chars con widechars.
Por ejemplo:

#include <stdio.h>
#include <wchar.h>
#include <locale.h>
#include <string.h>
int main() {
    setlocale(LC_ALL, "");
    char mitexto[64];
    wchar_t mitexto_w[128];
    printf("Este es una entrada de texto estándar:\n> ");
    scanf("%s", &mitexto);
    freopen(NULL, "r", stdin);
    freopen(NULL, "w", stdout);
    wprintf(L"Este es una entrada de texto widestring:\n> ");
    wscanf(L"%ls", &mitexto_w);
    freopen(NULL, "w", stdout);
    putchar('S');
    printf("\nEste es una salida de texto estándar: '%s'\n", mitexto);
    for(int i = 0; i <= strlen(mitexto); i++)
        printf("%i-%c\n", mitexto[i], mitexto[i]);
    freopen(NULL, "w", stdout);
    putwchar('W');
    wprintf(L"\nEste es una salida de texto widestring: '%ls'\n", mitexto_w);
    for(int i = 0; i <= wcslen(mitexto_w); i++)
        wprintf(L"%i-%lc\n", mitexto_w[i], mitexto_w[i]);
    return 0;
}

Nota: La L es un prefijo necesario para indicar que se trata de un texto longstring o widechar, este prefijo no se usa con fgetws o scanf, pero con wscanf y wprintf sí.

Librería Estándar de C - Manual de Referencia

increible clase.

buen clase