(suspiro pesado) El código original es INCORRECTO en estándar/K & R/ANSI C! ¡NO inicializa la cadena (la matriz de caracteres llamada str)! Me sorprendería si el ejemplo compilado. Lo que su segmento de programa realmente necesita es
if strcpy(str, "my cat is yellow")
{
/* everything went well, or at least one or more characters were copied. */
}
o, en caso que prometió no tratar de manipular la cadena, se puede utilizar un puntero char a la "mi gato es de color amarillo" cadena codificada en el código fuente.
Si, como se dijo, una "palabra" está delimitada por un carácter de espacio o un carácter NULO, entonces sería más rápido declarar un puntero de carácter y caminar hacia atrás del carácter justo antes de NULL. Obviamente, usted primero tiene que estar seguro de que había una cadena no vacía ....
#define NO_SPACE 20
#define ZERO_LENGTH -1
int iLen;
char *cPtr;
if (iLen=strlen(str)) /* get the number of characters in the sting */
{ /* there is at least one character in the string */
cPtr = (char *)(str + iLen); /* point to the NULL ending the string */
cPtr--; /* back up one character */
while (cPtr != str)
{ /* make sure there IS a space in the string
and that we don't walk too far back! */
if (' ' == *cPtr)
{ /* found a space */
/* Notice that we put the constant on the left?
That's insurance; the compiler would complain if we'd typed = instead of ==
*/
break;
}
cPtr--; /* walk back toward the beginning of the string */
}
if (cPtr != str)
{ /* found a space */
/* display the word and exit with the success code */
printf("The word is '%s'.\n", cPtr + 1);
exit (0);
}
else
{ /* oops. no space found in the string */
/* complain and exit with an error code */
fprintf(STDERR, "No space found.\n");
exit (NO_SPACE);
}
}
else
{ /* zero-length string. complain and exit with an error code. */
fprintf(STDERR, "Empty string.\n");
exit (ZERO_LENGTH);
}
Ahora se podría argumentar que cualquier carácter no alfabético debería marcar un límite de palabra, tales como "Perros- perseguidores "o" mi gato: amarillo ". En ese caso, sería fácil decir
if (!isalpha(*cPtr))
en el bucle en lugar de buscar sólo un espacio ....
Ese '+ 1' se puede hacer dentro de inicialización:' char * p = strrchr (str, '') + 1; ' – LihO
@LihO: Entonces se le dejará comprobar si el valor de retorno fue 1 (es decir, no encontrado). Esto no es una victoria –
@LihO Gracias :-) He añadido algunas comprobaciones para asegurarme de que el espacio no sea el último personaje. – cnicutar