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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs