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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more