For starters this array
char stringa[16] = "some string here";
does not contain a string because it does not have a space to accommodate the terminating zero character '\0'
of the string literal used as an initializer.
It would be better to declare it the following way without explicit specifying its size
char stringa[] = "some string here";
So this while loop
while (str[i])
can invoke undefined behavior.
Also you are using the uninitialized pointer str2
.
char *str2;
//...
str2[i] = toupper (str[0]);
that again invokes undefined behavior.
Pay attention to that a passed string can contain more than one space between words and moreover can contain leading and trailing spaces. So this if statement also can invoke undefined behavior due to skipping the terminating zero character '\0'
of the source string
if (str[i] == ' ')
{
str2[i] = str[i];
str2[i + 1] = toupper (str[i] + 1);
i += 2;
}
Hence your approach is in general wrong.
Such a function should return the modified source string.
Instead of the for loop it is better to use standard C functions strspn
and strcspn
.
Here is a demonstration program.
#include <string.h>
#include <stdio.h>
#include <ctype.h>
char * LetterCapitalize( char *s )
{
const char *delim = " \t";
for (char *p = s; *p; p += strcspn( p, delim ) )
{
p += strspn( p, delim );
if (*p) *p = toupper( ( unsigned char )*p );
}
return s;
}
int main( void )
{
char stringa[] = "some string here";
puts( stringa );
puts( LetterCapitalize( stringa ) );
}
The program output is
some string here
Some String Here