DEV Community

Lavender
Lavender

Posted on

C: Strings

char greetings[] = "Hello World!";
printf("%s", greetings);
Enter fullscreen mode Exit fullscreen mode

access string

char greetings[] = "Hello World!";
printf("%c", greetings[0]);
Enter fullscreen mode Exit fullscreen mode

modify string

char greetings[] = "Hello World!";
greetings[0] = 'J';
printf("%s", greetings);
// prints "Jello World!"
Enter fullscreen mode Exit fullscreen mode

Another way to create a string

char greetings[] = {'H','e','l','l','\0'};
printf("%s", greetings);
// print "Hell!"
Enter fullscreen mode Exit fullscreen mode

Creating String using character pointer (String Literals)

char *greetings = "Hello";
printf("%s", greetings);
// print "Hello!"
Enter fullscreen mode Exit fullscreen mode

NOTE: String literals might be stored in read-only section of memory. Modifying a string literal invokes undefined behavior. You can't modify it.!
C does not have a String type, use char type and create an array of characters

Useful links

Top comments (1)

Collapse
 
pauljlucas profile image
Paul J. Lucas

Your example for modifying a string is undefined behavior. (Whether it works in this particular case is irrelevant.) You can't modify a static string.