- Buying Guides

Complete Guides by How-To Geek
Our latest product roundups, reader favorites, more from how-to geek, latest geek news, latest reviews, across lifesavvy media.
Join 425,000 subscribers and get a daily digest of news, geek trivia, and our feature articles.
By submitting your email, you agree to the Terms of Use and Privacy Policy .
How to Work with Variables in Bash
Dave McKay first used computers when punched paper tape was in vogue, and he has been programming ever since. After over 30 years in the IT industry, he is now a full-time technology journalist. During his career, he has worked as a freelance programmer, manager of an international software development team, an IT services project manager, and, most recently, as a Data Protection Officer. His writing has been published by howtogeek.com, cloudsavvyit.com, itenterpriser.com, and opensource.com. Dave is a Linux evangelist and open source advocate. Read more...

Variables are vital if you want to write scripts and understand what that code you’re about to cut and paste from the web will do to your Linux computer. We’ll get you started!
Variables 101
Variables are named symbols that represent either a string or numeric value. When you use them in commands and expressions, they are treated as if you had typed the value they hold instead of the name of the variable.
To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore. Apart from that, you can use any mix of upper- and lowercase alphanumeric characters.
Here, we’ll create five variables. The format is to type the name, the equals sign = , and the value. Note there isn’t a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.
We’ll create four string variables and one numeric variable, this_year:
To see the value held in a variable, use the echo command. You must precede the variable name with a dollar sign $ whenever you reference the value it contains, as shown below:
Let’s use all of our variables at once:
The values of the variables replace their names. You can also change the values of variables. To assign a new value to the variable, my_boost , you just repeat what you did when you assigned its first value, like so:
If you re-run the previous command, you now get a different result:
So, you can use the same command that references the same variables and get different results if you change the values held in the variables.
We’ll talk about quoting variables later. For now, here are some things to remember:
- A variable in single quotes ' is treated as a literal string, and not as a variable.
- Variables in quotation marks " are treated as variables.
- To get the value held in a variable, you have to provide the dollar sign $ .
- A variable without the dollar sign $ only provides the name of the variable.
You can also create a variable that takes its value from an existing variable or number of variables. The following command defines a new variable called drink_of_the_Year, and assigns it the combined values of the my_boost and this_year variables:
How to Use Variables in Scripts
Scripts would be completely hamstrung without variables. Variables provide the flexibility that makes a script a general, rather than a specific, solution. To illustrate the difference, here’s a script that counts the files in the /dev directory.
Type this into a text file, and then save it as fcnt.sh (for “file count”):
Before you can run the script, you have to make it executable, as shown below:
Type the following to run the script:
This prints the number of files in the /dev directory. Here’s how it works:
- A variable called folder_to_count is defined, and it’s set to hold the string “/dev.”
- Another variable, called file_count , is defined. This variable takes its value from a command substitution. This is the command phrase between the parentheses $( ) . Note there’s a dollar sign $ before the first parenthesis. This construct $( ) evaluates the commands within the parentheses, and then returns their final value. In this example, that value is assigned to the file_count variable. As far as the file_count variable is concerned, it’s passed a value to hold; it isn’t concerned with how the value was obtained.
- The command evaluated in the command substitution performs an ls file listing on the directory in the folder_to_count variable, which has been set to “/dev.” So, the script executes the command “ls /dev.”
- The output from this command is piped into the wc command. The -l (line count) option causes wc to count the number of lines in the output from the ls command. As each file is listed on a separate line, this is the count of files and subdirectories in the “/dev” directory. This value is assigned to the file_count variable.
- The final line uses echo to output the result.
But this only works for the “/dev” directory. How can we make the script work with any directory? All it takes is one small change.
How to Use Command Line Parameters in Scripts
Many commands, such as ls and wc , take command line parameters. These provide information to the command, so it knows what you want it to do. If you want ls to work on your home directory and also to show hidden files , you can use the following command, where the tilde ~ and the -a (all) option are command line parameters:
Our scripts can accept command line parameters. They’re referenced as $1 for the first parameter, $2 as the second, and so on, up to $9 for the ninth parameter. (Actually, there’s a $0 , as well, but that’s reserved to always hold the script.)
You can reference command line parameters in a script just as you would regular variables. Let’s modify our script, as shown below, and save it with the new name fcnt2.sh :
This time, the folder_to_count variable is assigned the value of the first command line parameter, $1 .
The rest of the script works exactly as it did before. Rather than a specific solution, your script is now a general one. You can use it on any directory because it’s not hardcoded to work only with “/dev.”
Here’s how you make the script executable:
Now, try it with a few directories. You can do “/dev” first to make sure you get the same result as before. Type the following:
You get the same result (207 files) as before for the “/dev” directory. This is encouraging, and you get directory-specific results for each of the other command line parameters.
To shorten the script, you could dispense with the variable, folder_to_count , altogether, and just reference $1 throughout, as follows:
Working with Special Variables
We mentioned $0 , which is always set to the filename of the script. This allows you to use the script to do things like print its name out correctly, even if it’s renamed. This is useful in logging situations, in which you want to know the name of the process that added an entry.
The following are the other special preset variables:
- $# : How many command line parameters were passed to the script.
- [email protected] : All the command line parameters passed to the script.
- $? : The exit status of the last process to run.
- $$ : The Process ID (PID) of the current script.
- $USER : The username of the user executing the script.
- $HOSTNAME : The hostname of the computer running the script.
- $SECONDS : The number of seconds the script has been running for.
- $RANDOM : Returns a random number.
- $LINENO : Returns the current line number of the script.
You want to see all of them in one script, don’t you? You can! Save the following as a text file called, special.sh :
Type the following to make it executable:
Now, you can run it with a bunch of different command line parameters, as shown below.
Environment Variables
Bash uses environment variables to define and record the properties of the environment it creates when it launches. These hold information Bash can readily access, such as your username, locale, the number of commands your history file can hold, your default editor, and lots more.
To see the active environment variables in your Bash session, use this command:
If you scroll through the list, you might find some that would be useful to reference in your scripts.
How to Export Variables
When a script runs, it’s in its own process, and the variables it uses cannot be seen outside of that process. If you want to share a variable with another script that your script launches, you have to export that variable. We’ll show you how to this with two scripts.
First, save the following with the filename script_one.sh :
This creates two variables, first_var and second_var , and it assigns some values. It prints these to the terminal window, exports the variables, and calls script_two.sh . When script_two.sh terminates, and process flow returns to this script, it again prints the variables to the terminal window. Then, you can see if they changed.
The second script we’ll use is script_two.sh . This is the script that script_one.sh calls. Type the following:
This second script prints the values of the two variables, assigns new values to them, and then prints them again.
To run these scripts, you have to type the following to make them executable:
And now, type the following to launch script_one.sh :
This is what the output tells us:
- script_one.sh prints the values of the variables, which are alpha and bravo.
- script_two.sh prints the values of the variables (alpha and bravo) as it received them.
- script_two.sh changes them to charlie and delta.
- script_one.sh prints the values of the variables, which are still alpha and bravo.
What happens in the second script, stays in the second script. It’s like copies of the variables are sent to the second script, but they’re discarded when that script exits. The original variables in the first script aren’t altered by anything that happens to the copies of them in the second.
How to Quote Variables
You might have noticed that when scripts reference variables, they’re in quotation marks " . This allows variables to be referenced correctly, so their values are used when the line is executed in the script.
If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter.
Here’s an example:
Bash sees the space before “Geek” as an indication that a new command is starting. It reports that there is no such command, and abandons the line. echo shows us that the site_name variable holds nothing—not even the “How-To” text.
Try that again with quotation marks around the value, as shown below:
This time, it’s recognized as a single value and assigned correctly to the site_name variable.
echo Is Your Friend
It can take some time to get used to command substitution, quoting variables, and remembering when to include the dollar sign.
Before you hit Enter and execute a line of Bash commands, try it with echo in front of it. This way, you can make sure what’s going to happen is what you want. You can also catch any mistakes you might have made in the syntax.
RELATED: Best Linux Laptops for Developers and Enthusiasts
- › How to Tell If a Bash String Contains a Substring on Linux
- › How to Use Case Statements in Bash Scripts
- › How to Use the Echo Command on Linux
- › How to Validate the Syntax of a Linux Bash Script Before Running It
- › How to Use eval in Linux Bash Scripts
- › How to Use the Bash printf Command on Linux
- › How to Use the cd Command on Linux
- › Tribit StormBox Blast Review: A Portable Bluetooth Party Starter
Python Tutorial
File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python string variables, assign string to a variable.
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
Related Pages

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
String assignment in C#
A few weeks ago, I discovered that strings in C# are defined as reference types and not value types. Initially I was confused about this, but then after some reading, I suddenly understood why it is important to store strings on the heap and not the stack - because it would be very inefficient to have a very large string that gets copied over an unpredictable number of stack frames. I completely accept this.
I feel that my understanding is almost complete, but there is one element that I am missing - what language feature do strings use to keep them immutable? To illustrate with a code example:
I do not understand what language feature makes a copy of valueA when I assign it to valueB. Or perhaps, the reference to valueA does not change when I assign it to valueB, only valueA gets a new reference to itself when I set the string. As this is an instance type, I do not understand why this works.
I understand that you can overload, for example, the == and != operators, but I cannot seem to find any documentation on overloading the = operators. What is the explanation?
- heap-memory

- 1 Of course you're talking about language feature, but immutability isn't the correct term here (it's just about the class, as Jason says). In C# assignments are done by copying the reference, not assigning the reference itself. May be you should see this too: c-sharp-reference-assignment-operator – nawfal Jan 16, 2014 at 21:27
- I like to read it as if it was doing this, string valueA = new String("FirstValue"); string valueB = valueA; valueA = new String("AnotherValue"); – bgura Mar 5, 2015 at 20:11
3 Answers 3
what language feature do strings use to keep them immutable?
It is not a language feature. It is the way the class is defined.
For example,
is like an int except it's a reference type, but it's immutable. We defined it to be so. We can define it to be mutable too:
I do not understand what language feature makes a copy of valueA when I assign it to valueB .
It doesn't copy the string , it copies the reference. string s are reference type. This means that variables of type string s are storage locations whose values are references. In this case, their values are references to instances of string . When you assign a variable of type string to another of type string , the value is copied. In this case, the value is a reference and it is copied by the assignment. This is true for any reference type, not just string or only immutable reference types.
Or perhaps, the reference to valueA does not change when I assign it to valueB , only valueA gets a new reference to itself when i set the string.
Nope, the values of valueA and valueB refer to the same instance of string . Their values are references, and those values are equal. If you could somehow mutate * the instance of string referred to by valueA , the referrent of both valueA and valueB would see this mutation.
As this is an instance type, I do not understand why this works.
There is no such thing as an instance type.
Basically, string s are reference types. But string are immutable. When you mutate a string , what happens is that you get a reference to a new string that is the result of the mutation to the already existing string .
Here, s and t are variables whose values refer to the same instance of string . The referrent of s is not mutated by the call to String.ToUpper . Instead, s.ToUpper makes a mutation of the referrent of s and returns a reference to a new instance of string that it creates in the process of apply the mutation. We assign that reference to u .
I understand that you can overload, for example, the == and != operators, but I cannot seem to find any documentation on overloading the = operators.
You can't overload = .
* You can, with some tricks. Ignore them.
First of all, your example will work the same to any reference variables, not just strings.
What happens is:
Now the immutability is a different concept. It means that the value itself can't be changed. This will show up in a situation like this:
This is because of String's immutability, valueA doesn't change the string itself... It creates a new COPY with the changes and references that.
- 3 While your answer explains the first part well, your point on immutability is not very correct. valueA.Replace('F', 'B') will leave valueA with "FirstValue" still, that's how immutable they are. – nawfal Jan 16, 2014 at 21:20
- 3 string.Replace(this string, char, char) literally returns a new string as a return value. I'm not sure that the second example above, demonstrates immutability, because the return value is not used in the assertion. Please clarify. Thanks. – Phil Jan 30, 2017 at 16:07
- I think he meant valueA = valueA.Replace('F','B'); – John Aug 28, 2017 at 15:43
Or perhaps, the reference to valueA does not change when I assign it to valueB, only valueA gets a new reference to itself when i set the string.
That is correct. As strings are immutable, there is no problem having two variables referencing the same string object. When you assign a new string to one of them, it's the reference that is replaced, not the string object.
I cannot seem to find any documentation on overloading the = operators.
That is not due to any shortcoming on your side, it's because there is no way to overload the assignment operator in C#.
The = operator is quite simple, it takes the value on the right hand side and assigns to the variable on the left hand side. If it's a reference type, the value is the reference, so that is what's assigned.
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged c# string reference heap-memory or ask your own question .
- The Overflow Blog
- Five Stack Exchange sites turned ten years old this quarter!
- “Move fast and break things” doesn’t apply to other people’s savings (Ep. 544)
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- One-day-ahead prediction of S&P500 with Temporal Convolutional Networks
- Are condensed sets (locally) cartesian closed?
- What laws would Jesus be breaking if he were to turn water into wine today?
- Question about sample size indicated from power analysis for chi-square analysis in Python
- Why does Jesus change the speech from who is the greatest to who is the first?
- Intuition on "sharper" Cayley theorem
- Checksum of secret data
- Are there any sources with high-confidence state vectors for GRAIL-A?
- Do Catholic anathemas apply to people who lived before it was codified?
- Pixel 5 vibrates once when turned face down
- Are there any medieval manuals relating to castle building?
- Does every US state set its standard deduction to match the federal one? Why?
- Is this a viable theoretical method of fast interplanetary space travel?
- Does Hooke's Law apply to all springs?
- How do/should administrators estimate the cost of producing an online introductory mathematics class?
- Chimeric Animals from Icewind Dale
- What do we really know about lotteries?
- Google maps for Space exploration
- Does single case chance actually exist?
- What are the Stargate dial home device symbols used to dial Earth from Atlantis?
- Does Queueable Apex guarantee preventing deadlocks if implemented correctly?
- Is it inappropriate to tell my boss that "baby talk" is unprofessional?
- Why is the work done by the tension in a pendulum string 0?
- Imtiaz Germain Primes
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
cppreference.com
Std::basic_string<chart,traits,allocator>:: assign.
Replaces the contents of the string.
[ edit ] Parameters
[ edit ] return value, [ edit ] complexity, [ edit ] exceptions.
If an exception is thrown for any reason, this function has no effect (strong exception guarantee). (since C++11)
If the operation would result in size() > max_size() , throws std::length_error .
[ edit ] Example
[ edit ] defect reports.
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
[ edit ] See also
- conditionally noexcept
- Recent changes
- Offline version
- What links here
- Related changes
- Upload file
- Special pages
- Printable version
- Permanent link
- Page information
- In other languages
- This page was last modified on 22 January 2023, at 16:30.
- This page has been accessed 160,393 times.
- Privacy policy
- About cppreference.com
- Disclaimers

- Skip to main content
- Skip to search
- Skip to select language
- Get MDN Plus
- English (US)
Handling text — strings in JavaScript
- Overview: First steps
Next, we'll turn our attention to strings — this is what pieces of text are called in programming. In this article, we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in strings, and joining strings together.
The power of words
Words are very important to humans — they are a large part of how we communicate. Since the Web is a largely text-based medium designed to allow humans to communicate and share information, it is useful for us to have control over the words that appear on it. HTML provides structure and meaning to our text, CSS allows us to precisely style it, and JavaScript contains a number of features for manipulating strings, creating custom welcome messages and prompts, showing the right text labels when needed, sorting terms into the desired order, and much more.
Pretty much all of the programs we've shown you so far in the course have involved some string manipulation.
Strings — the basics
Strings are dealt with similarly to numbers at first glance, but when you dig deeper you'll start to see some notable differences. Let's start by entering some basic lines into the browser developer console to familiarize ourselves.
Creating a string
- To start with, enter the following lines: const string = "The revolution will not be televised." ; console . log ( string ) ; Just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value. The only difference here is that when writing a string, you need to surround the value with quotes.
- If you don't do this, or miss one of the quotes, you'll get an error. Try entering the following lines: const badString1 = This is a test ; const badString2 = 'This is a test ; const badString3 = This is a test' ; These lines don't work because any text without quotes around it is assumed to be a variable name, property name, a reserved word, or similar. If the browser can't find it, then an error is raised (e.g. "missing; before statement"). If the browser can see where a string starts, but can't find the end of the string, as indicated by the 2nd quote, it complains with an error (with "unterminated string literal"). If your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks.
- The following will work if you previously defined the variable string — try it now: const badString = string ; console . log ( badString ) ; badString is now set to have the same value as string .
Single quotes vs. double quotes
- In JavaScript, you can choose single quotes or double quotes to wrap your strings in. Both of the following will work okay: const sgl = 'Single quotes.' ; const dbl = "Double quotes" ; console . log ( sgl ) ; console . log ( dbl ) ;
- There is very little difference between the two, and which you use is down to personal preference. You should choose one and stick to it, however; differently quoted code can be confusing, especially if you use two different quotes on the same string! The following will return an error: const badQuotes = 'What on earth ? " ;
- The browser will think the string has not been closed because the other type of quote you are not using to contain your strings can appear in the string. For example, both of these are okay: const sglDbl = 'Would you eat a "fish supper"?' ; const dblSgl = "I'm feeling blue." ; console . log ( sglDbl ) ; console . log ( dblSgl ) ;
- However, you can't include the same quote mark inside the string if it's being used to contain them. The following will error, as it confuses the browser as to where the string ends: const bigmouth = 'I' ve got no right to take my place…' ; This leads us very nicely into our next subject.
Escaping characters in a string
To fix our previous problem code line, we need to escape the problem quote mark. Escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character. Try this:
This works fine. You can escape other characters in the same way, e.g. \" , and there are some special codes besides. See Escape sequences for more details.
Concatenating strings
Concatenate just means "join together". To join together strings in JavaScript you can use a different type of string, called a template literal .
A template literal looks just like a normal string, but instead of using single or double quote marks ( ' or " ), you use backtick characters ( ` ):
This can work just like a normal string, except you can include variables in it, wrapped inside ${ } characters, and the variable's value will be inserted into the result:
You can use the same technique to join together two variables:
Concatenation in context
Let's have a look at concatenation being used in action:
Here we're using the window.prompt() function, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given variable — in this case name . We then use the window.alert() function to display another popup containing a string which inserts the name into a generic greeting message.
Concatenation using "+"
You can also concatenate strings using the + operator:
However, template literals usually give you more readable code:
Numbers vs. strings
So what happens when we try to combine a string and a number? Let's try it in our console:
You might expect this to return an error, but it works just fine. Trying to represent a string as a number doesn't really make sense, but representing a number as a string does, so the browser converts the number to a string and concatenates the two strings.
If you have a numeric variable that you want to convert to a string but not change otherwise, or a string variable that you want to convert to a number but not change otherwise, you can use the following two constructs:
- The Number() function converts anything passed to it into a number, if it can. Try the following: const myString = "123" ; const myNum = Number ( myString ) ; console . log ( typeof myNum ) ;
- Conversely, every number has a method called toString() that converts it to the equivalent string. Try this: const myNum2 = 123 ; const myString2 = myNum2 . toString ( ) ; console . log ( typeof myString2 ) ;
These constructs can be really useful in some situations. For example, if a user enters a number into a form's text field, it's a string. However, if you want to add this number to something, you'll need it to be a number, so you could pass it through Number() to handle this. We did exactly this in our Number Guessing Game, in line 59 .
Including expressions in strings
You can include JavaScript expressions in template literals, as well as simple variables, and the results will be included in the result:
Multiline strings
Template literals respect the line breaks in the source code, so you can write strings that span multiple lines like this:
To have the equivalent output using a normal string you'd have to include line break characters ( \n ) in the string:
See our Template literals reference page for more examples and details of advanced features.
So that's the very basics of strings covered in JavaScript. In the next article, we'll build on this, looking at some of the built-in methods available to strings in JavaScript and how we can use them to manipulate our strings into just the form we want.
This Women's Day, sharpen your C Programming skills with PRO.
Learn C practically and Get Certified .
Popular Tutorials
Popular examples, reference materials.
Learn C Interactively
Interactive C Course
C introduction.
- Keywords & Identifier
- Variables & Constants
- C Data Types
- C Input/Output
- C Operators
- C Introduction Examples
C Flow Control
- C if...else
- C while Loop
- C break and continue
- C switch...case
- C Programming goto
- Control Flow Examples
C Functions
- C Programming Functions
- C User-defined Functions
- C Function Types
- C Recursion
- C Storage Class
- C Function Examples
- C Programming Arrays
- C Multi-dimensional Arrays
- C Arrays & Function
- C Programming Pointers
- C Pointers & Arrays
- C Pointers And Functions
- C Memory Allocation
- Array & Pointer Examples
C Programming Strings
- C Programming String
- C String Functions
- C String Examples
Structure And Union
- C Structure
- C Struct & Pointers
- C Struct & Function
- C struct Examples
C Programming Files
- C Files Input/Output
C Files Examples
Additional Topics
- C Enumeration
- C Preprocessors
- C Standard Library
- C Programming Examples

Related Topics
String Manipulations In C Programming Using Library Functions
- Remove all Characters in a String Except Alphabets
- Find the Frequency of Characters in a String
- Sort Elements in Lexicographical Order (Dictionary Order)
Relationship Between Arrays and Pointers
In this tutorial, you'll learn about strings in C programming. You'll learn to declare them, initialize them and use them for various I/O operations with the help of examples.
Video: C Strings
In C programming, a string is a sequence of characters terminated with a null character \0 . For example:
When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default.

- How to declare a string?
Here's how you can declare strings:

Here, we have declared a string of 5 characters.
- How to initialize strings?
You can initialize strings in a number of ways.

Let's take another example:
Here, we are trying to assign 6 characters (the last character is '\0' ) to a char array having 5 characters. This is bad and you should never do this.
Assigning Values to Strings
Arrays and strings are second-class citizens in C; they do not support the assignment operator once it is declared. For example,
Note: Use the strcpy() function to copy the string instead.
Read String from the user
You can use the scanf() function to read a string.
The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).
Example 1: scanf() to read a string
Even though Dennis Ritchie was entered in the above program, only "Dennis" was stored in the name string. It's because there was a space after Dennis .
Also notice that we have used the code name instead of &name with scanf() .
This is because name is a char array, and we know that array names decay to pointers in C.
Thus, the name in scanf() already points to the address of the first element in the string, which is why we don't need to use & .
How to read a line of text?
You can use the fgets() function to read a line of string. And, you can use puts() to display the string.
Example 2: fgets() and puts()
Here, we have used fgets() function to read a string from the user.
fgets(name, sizeof(name), stdlin); // read string
The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the size of the name string.
To print the string, we have used puts(name); .
Note: The gets() function can also be to take input from the user. However, it is removed from the C standard. It's because gets() allows you to input any length of characters. Hence, there might be a buffer overflow.
Passing Strings to Functions
Strings can be passed to a function in a similar way as arrays. Learn more about passing arrays to a function .
Example 3: Passing string to a Function
Strings and pointers.
Similar like arrays, string names are "decayed" to pointers. Hence, you can use pointers to manipulate elements of the string. We recommended you to check C Arrays and Pointers before you check this example.
Example 4: Strings and Pointers
Commonly used string functions.
- strlen() - calculates the length of a string
- strcpy() - copies a string to another
- strcmp() - compares two strings
- strcat() - concatenates two strings
Table of Contents
- Read and Write String: gets() and puts()
- Passing strings to a function
- Strings and pointers
- Commonly used string functions
Sorry about that.
Related Tutorials
C Input Output (I/O)
Try PRO for FREE
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
- Mastering Data Analytics
- DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Java Tutorial
- Introduction to Java
- Similarities and Difference between Java and C++
- Setting up the environment in Java
- Java Basic Syntax
- Java Hello World Program
- Differences between JDK, JRE and JVM
- How JVM Works – JVM Architecture?
- Java Identifiers
- Variables in Java
- Scope of Variables In Java
- Data types in Java
- Operators in Java
- Java Arithmetic Operators with Examples
- Java Assignment Operators with Examples
- Java Unary Operator with Examples
- Java Relational Operators with Examples
- Java Logical Operators with Examples
- Java Ternary Operator with Examples
- Bitwise Operators in Java
- Packages In Java
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else statement with Examples
- Java if-else-if ladder with Examples
- Loops in Java
- Java For loop with Examples
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- return keyword in Java
- Arrays in Java
- Multidimensional Arrays in Java
- Jagged Array in Java
Strings in Java
- String class in Java
- StringBuffer class in Java
- StringBuilder Class in Java with Examples
- Object Oriented Programming (OOPs) Concept in Java
- Classes and Objects in Java
- Methods in Java
- Access Modifiers in Java
- Wrapper Classes in Java
- Need of Wrapper Classes in Java
- Constructors in Java
- Copy Constructor in Java
- Constructor Chaining In Java with Examples
- Private Constructors and Singleton Classes in Java
- Inheritance in Java
- Java and Multiple Inheritance
- Comparison of Inheritance in C++ and Java
- Polymorphism in Java
- Dynamic Method Dispatch or Runtime Polymorphism in Java
- Method Overloading in Java
- Different ways of Method Overloading in Java
- Overriding in Java
- Difference Between Method Overloading and Method Overriding in Java
- Abstraction in Java
- Abstract Class in Java
- Difference between Abstract Class and Interface in Java
- Encapsulation in Java
- Interfaces in Java
- Nested Interface in Java
- Marker interface in Java
- Functional Interfaces in Java
- Comparator Interface in Java with Examples
- List of all Java Keywords
- Super Keyword in Java
- final Keyword in Java
- abstract keyword in java
- static Keyword in Java
- ‘this’ reference in Java
- enum in Java
- Exceptions in Java
- Types of Exception in Java with Examples
- Checked vs Unchecked Exceptions in Java
- Try, catch, throw and throws in Java
- Flow control in try catch finally in Java
- throw and throws in Java
- User-defined Custom Exception in Java
- Collections in Java
- Collections Class in Java
- List Interface in Java with Examples
- ArrayList in Java
- Vector Class in Java
- Stack Class in Java
- LinkedList in Java
- Queue Interface In Java
- PriorityQueue in Java
- Deque interface in Java with Example
- ArrayDeque in Java
- Set in Java
- HashSet in Java
- LinkedHashSet in Java with Examples
- SortedSet Interface in Java with Examples
- NavigableSet in Java with Examples
- TreeSet in Java
- Map Interface in Java
- HashMap in Java with Examples
- Hashtable in Java
- LinkedHashMap in Java
- SortedMap Interface in Java with Examples
- TreeMap in Java
- Multithreading in Java
- Lifecycle and States of a Thread in Java
- Main thread in Java
- Java Thread Priority in Multithreading
- Thread Pools in Java
- Synchronization in Java
- Method and Block Synchronization in Java
- Importance of Thread Synchronization in Java
- Thread Safety and how to achieve it in Java
- Difficulty Level : Easy
- Last Updated : 28 Nov, 2022
In the given example only one object will be created. Firstly JVM will not find any string object with the value “Welcome” in the string constant pool, so it will create a new object. After that it will find the string with the value “Welcome” in the pool, it will not create a new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool.
Why Java uses the concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).
Using new keyword
- String s = new String(“Welcome”);
- In such a case, JVM will create a new string object in normal (non-pool) heap memory and the literal “Welcome” will be placed in the string constant pool. The variable s will refer to the object in the heap (non-pool).
Syntax:
Example:
Memory allotment of String
Whenever a String Object is created as a literal, the object will be created in the String constant pool. This allows JVM to optimize the initialization of String literal.
Example:
The string can also be declared using a new operator i.e. dynamically allocated. In case of String are dynamically allocated they are assigned a new memory location in the heap. This string will not be added to String constant pool.
Example:
If you want to store this string in the constant pool then you will need to “intern” it.
It is preferred to use String literals as it allows JVM to optimize memory allocation.
An example that shows how to declare a String
Interfaces and Classes in Strings in Java
CharBuffer : This class implements the CharSequence interface. This class is used to allow character buffers to be used in place of CharSequences. An example of such usage is the regular-expression package java.util.regex.
String : It is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created.
Ways of Creating a String
There are two ways to create a string in Java:
- String Literal
- Using new Keyword
String literal
StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences.
StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters.
StringTokenizer class in Java is used to break a string into tokens.
A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object.
StringJoiner is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. Though this can also be with the help of StringBuilder class to append delimiter after each string, StringJoiner provides an easy way to do that without much code to write.
Above we saw we can create a string by String Literal.
For ex- // String s=”Welcome”;
Here the JVM checks the String Constant Pool. If the string does not exist, then a new string instance is created and placed in a pool. If the string exists, then it will not create a new object. Rather, it will return the reference to the same instance. The cache that stores these string instances is known as the String Constant pool or String Pool. In earlier versions of Java up to JDK 6 String pool was located inside PermGen(Permanent Generation) space. But in JDK 7 it is moved to the main heap area.
Why did the String pool move from PermGen to the normal heap area?
PermGen space is limited, the default size is just 64 MB. it was a problem with creating and storing too many string objects in PermGen space. That’s why the String pool was moved to a larger heap area. To make Java more memory efficient, the concept of string literal is used. By the use of the ‘new’ keyword, The JVM will create a new string object in the normal heap area even if the same string object is present in the string pool.
For example:
String a=new String(“Bhubaneswar”)
Let us have a look at the concept with a java program and visualize the actual JVM memory structure:
Note: All objects in Java are stored in a heap. The reference variable is to the object stored in the stack area or they can be contained in other objects which puts them in the heap area also.
Example 1:
Immutable String in Java
- In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
- Once a string object is created its data or state can’t be changed but a new string object is created.
Here Sachin is not changed but a new object is created with “Sachin Tendulkar”. That is why a string is known as immutable.
As you can see in the given figure that two objects are created but s reference variable still refers to “Sachin” and not to “Sachin Tendulkar”. But if we explicitly assign it to the reference variable, it will refer to the “Sachin Tendulkar” object.
For Example:
Why string objects are immutable in java? Because java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object “sachin”. If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
Please Login to comment...
- anthonycathers
- bitsandbytes
- Satyabrata_Jena
- singhankitasingh066
- aditiyadav20102001
- kamleshjoshi18
- gowthammallela231
- java-StringBuffer
- Java-StringBuilder
- Java-Strings
New Course Launch!
Improve your Coding Skills with Practice
Start your coding journey now.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
String Basics in Visual Basic
- 3 minutes to read
- 11 contributors
The String data type represents a series of characters (each representing in turn an instance of the Char data type). This topic introduces the basic concepts of strings in Visual Basic.
String Variables
An instance of a string can be assigned a literal value that represents a series of characters. For example:
A String variable can also accept any expression that evaluates to a string. Examples are shown below:
Any literal that is assigned to a String variable must be enclosed in quotation marks (""). This means that a quotation mark within a string cannot be represented by a quotation mark. For example, the following code causes a compiler error:
This code causes an error because the compiler terminates the string after the second quotation mark, and the remainder of the string is interpreted as code. To solve this problem, Visual Basic interprets two quotation marks in a string literal as one quotation mark in the string. The following example demonstrates the correct way to include a quotation mark in a string:
In the preceding example, the two quotation marks preceding the word Look become one quotation mark in the string. The three quotation marks at the end of the line represent one quotation mark in the string and the string termination character.
String literals can contain multiple lines:
The resulting string contains newline sequences that you used in your string literal (vbcr, vbcrlf, etc.). You no longer need to use the old workaround:
Characters in Strings
A string can be thought of as a series of Char values, and the String type has built-in functions that allow you to perform many manipulations on a string that resemble the manipulations allowed by arrays. Like all array in .NET Framework, these are zero-based arrays. You may refer to a specific character in a string through the Chars property, which provides a way to access a character by the position in which it appears in the string. For example:
In the above example, the Chars property of the string returns the fourth character in the string, which is D , and assigns it to myChar . You can also get the length of a particular string through the Length property. If you need to perform multiple array-type manipulations on a string, you can convert it to an array of Char instances using the ToCharArray function of the string. For example:
The variable myArray now contains an array of Char values, each representing a character from myString .
The Immutability of Strings
A string is immutable , which means its value cannot be changed once it has been created. However, this does not prevent you from assigning more than one value to a string variable. Consider the following example:
Here, a string variable is created, given a value, and then its value is changed.
More specifically, in the first line, an instance of type String is created and given the value This string is immutable . In the second line of the example, a new instance is created and given the value Or is it? , and the string variable discards its reference to the first instance and stores a reference to the new instance.
Unlike other intrinsic data types, String is a reference type. When a variable of reference type is passed as an argument to a function or subroutine, a reference to the memory address where the data is stored is passed instead of the actual value of the string. So in the previous example, the name of the variable remains the same, but it points to a new and different instance of the String class, which holds the new value.
- Introduction to Strings in Visual Basic
- String Data Type
- Char Data Type
- Basic String Operations
Submit and view feedback for
Additional resources
- <cassert> (assert.h)
- <cctype> (ctype.h)
- <cerrno> (errno.h)
- C++11 <cfenv> (fenv.h)
- <cfloat> (float.h)
- C++11 <cinttypes> (inttypes.h)
- <ciso646> (iso646.h)
- <climits> (limits.h)
- <clocale> (locale.h)
- <cmath> (math.h)
- <csetjmp> (setjmp.h)
- <csignal> (signal.h)
- <cstdarg> (stdarg.h)
- C++11 <cstdbool> (stdbool.h)
- <cstddef> (stddef.h)
- C++11 <cstdint> (stdint.h)
- <cstdio> (stdio.h)
- <cstdlib> (stdlib.h)
- <cstring> (string.h)
- C++11 <ctgmath> (tgmath.h)
- <ctime> (time.h)
- C++11 <cuchar> (uchar.h)
- <cwchar> (wchar.h)
- <cwctype> (wctype.h)
Containers:
- C++11 <array>
- <deque>
- C++11 <forward_list>
- <list>
- <map>
- <queue>
- <set>
- <stack>
- C++11 <unordered_map>
- C++11 <unordered_set>
- <vector>
Input/Output:
- <fstream>
- <iomanip>
- <ios>
- <iosfwd>
- <iostream>
- <istream>
- <ostream>
- <sstream>
- <streambuf>
Multi-threading:
- C++11 <atomic>
- C++11 <condition_variable>
- C++11 <future>
- C++11 <mutex>
- C++11 <thread>
- <algorithm>
- <bitset>
- C++11 <chrono>
- C++11 <codecvt>
- <complex>
- <exception>
- <functional>
- C++11 <initializer_list>
- <iterator>
- <limits>
- <locale>
- <memory>
- <new>
- <numeric>
- C++11 <random>
- C++11 <ratio>
- C++11 <regex>
- <stdexcept>
- <string>
- C++11 <system_error>
- C++11 <tuple>
- C++11 <type_traits>
- C++11 <typeindex>
- <typeinfo>
- <utility>
- <valarray>
class templates
- basic_string
- char_traits
- C++11 u16string
- C++11 u32string
- C++11 stold
- C++11 stoll
- C++11 stoul
- C++11 stoull
- C++11 to_string
- C++11 to_wstring
- string::~string
- string::string
member functions
- string::append
- string::assign
- C++11 string::back
- string::begin
- string::c_str
- string::capacity
- C++11 string::cbegin
- C++11 string::cend
- string::clear
- string::compare
- string::copy
- C++11 string::crbegin
- C++11 string::crend
- string::data
- string::empty
- string::end
- string::erase
- string::find
- string::find_first_not_of
- string::find_first_of
- string::find_last_not_of
- string::find_last_of
- C++11 string::front
- string::get_allocator
- string::insert
- string::length
- string::max_size
- string::operator[]
- string::operator+=
- string::operator=
- C++11 string::pop_back
- string::push_back
- string::rbegin
- string::rend
- string::replace
- string::reserve
- string::resize
- string::rfind
- C++11 string::shrink_to_fit
- string::size
- string::substr
- string::swap
member constants
- string::npos
non-member overloads
- getline (string)
- operator+ (string)
- operator<< (string)
- >/" title="operator>> (string)"> operator>> (string)
- relational operators (string)
- swap (string)
std:: string ::operator=
Return value, iterator validity, exception safety.
C String – How to Declare Strings in the C Programming Language
Computers store and process all kinds of data.
Strings are just one of the many forms in which information is presented and gets processed by computers.
Strings in the C programming language work differently than in other modern programming languages.
In this article, you'll learn how to declare strings in C.
Before doing so, you'll go through a basic overview of what data types, variables, and arrays are in C. This way, you'll understand how these are all connected to one another when it comes to working with strings in C.
Knowing the basics of those concepts will then help you better understand how to declare and work with strings in C.
Let's get started!
Data types in C
C has a few built-in data types.
They are int , short , long , float , double , long double and char .
As you see, there is no built-in string or str (short for string) data type.
The char data type in C
From those types you just saw, the only way to use and present characters in C is by using the char data type.
Using char , you are able to to represent a single character – out of the 256 that your computer recognises. It is most commonly used to represent the characters from the ASCII chart.
The single characters are surrounded by single quotation marks .
The examples below are all char s – even a number surrounded by single quoation marks and a single space is a char in C:
Every single letter, symbol, number and space surrounded by single quotation marks is a single piece of character data in C.
What if you want to present more than one single character?
The following is not a valid char – despite being surrounded by single quotation marks. This is because it doesn't include only a single character inside the single quotation marks:
'freeCodeCamp is awesome'
When many single characters are strung together in a group, like the sentence you see above, a string is created. In that case, when you are using strings, instead of single quotation marks you should only use double quotation marks.
"freeCodeCamp is awesome"
How to declare variables in C
So far you've seen how text is presented in C.
What happens, though, if you want to store text somewhere? After all, computers are really good at saving information to memory for later retrieval and use.
The way you store data in C, and in most programming languages, is in variables.
Essentially, you can think of variables as boxes that hold a value which can change throughout the life of a program. Variables allocate space in the computer's memory and let C know that you want some space reserved.
C is a statically typed language, meaning that when you create a variable you have to specify what data type that variable will be.
There are many different variable types in C, since there are many different kinds of data.
Every variable has an associated data type.
When you create a variable, you first mention the type of the variable (wether it will hold integer, float, char or any other data values), its name, and then optionally, assign it a value:
Be careful not to mix data types when working with variables in C, as that will cause errors.
For intance, if you try to change the example from above to use double quotation marks (remember that chars only use single quotation marks), you'll get an error when you compile the code:
As mentioned earlier on, C doesn't have a built-in string data type. That also means that C doesn't have string variables!
How to create arrays in C
An array is essentially a variable that stores multiple values. It's a collection of many items of the same type.
As with regular variables, there are many different types of arrays because arrays can hold only items of the same data type. There are arrays that hold only int s, only float s, and so on.
This is how you define an array of ints s for example:
First you specify the data type of the items the array will hold. Then you give it a name and immediately after the name you also include a pair of square brackets with an integer. The integer number speficies the length of the array.
In the example above, the array can hold 3 values.
After defining the array, you can assign values individually, with square bracket notation, using indexing. Indexing in C (and most programming languages) starts at 0 .
You reference and fetch an item from an array by using the name of the array and the item's index in square brackets, like so:
What are character arrays in C?
So, how does everything mentioned so far fit together, and what does it have to do with initializing strings in C and saving them to memory?
Well, strings in C are actually a type of array – specifically, they are a character array . Strings are a collection of char values.
How strings work in C
In C, all strings end in a 0 . That 0 lets C know where a string ends.
That string-terminating zero is called a string terminator . You may also see the term null zero used for this, which has the same meaning.
Don't confuse this final zero with the numeric integer 0 or even the character '0' - they are not the same thing.
The string terminator is added automatically at the end of each string in C. But it is not visible to us – it's just always there.
The string terminator is represented like this: '\0' . What sets it apart from the character '0' is the backslash it has.
When working with strings in C, it's helpful to picture them always ending in null zero and having that extra byte at the end.

Each character takes up one byte in memory.
The string "hello" , in the picture above, takes up 6 bytes .
"Hello" has five letters, each one taking up 1 byte of space, and then the null zero takes up one byte also.
The length of strings in C
The length of a string in C is just the number of characters in a word, without including the string terminator (despite it always being used to terminate strings).
The string terminator is not accounted for when you want to find the length of a string.
For example, the string freeCodeCamp has a length of 12 characters.
But when counting the length of a string, you must always count any blank spaces too.
For example, the string I code has a length of 6 characters. I is 1 character, code has 4 characters, and then there is 1 blank space.
So the length of a string is not the same number as the number of bytes that it has and the amount of memory space it takes up.
How to create character arrays and initialize strings in C
The first step is to use the char data type. This lets C know that you want to create an array that will hold characters.
Then you give the array a name, and immediatelly after that you include a pair of opening and closing square brackets.
Inside the square brackets you'll include an integer. This integer will be the largest number of characters you want your string to be including the string terminator.
You can initialise a string one character at a time like so:
But this is quite time-consuming. Instead, when you first define the character array, you have the option to assign it a value directly using a string literal in double quotes:
If you want, istead of including the number in the square brackets, you can only assign the character array a value.
It works exactly the same as the example above. It will count the number of characters in the value you provide and automatically add the null zero character at the end:
Remember, you always need to reserve enough space for the longest string you want to include plus the string terminator.
If you want more room, need more memory, and plan on changing the value later on, include a larger number in the square brackets:
How to change the contents of a character array
So, you know how to initialize strings in C. What if you want to change that string though?
You cannot simply use the assignment operator ( = ) and assign it a new value. You can only do that when you first define the character array.
As seen earlier on, the way to access an item from an array is by referencing the array's name and the item's index number.
So to change a string, you can change each character individually, one by one:
That method is quite cumbersome, time-consuming, and error-prone, though. It definitely is not the preferred way.
You can instead use the strcpy() function, which stands for string copy .
To use this function, you have to include the #include <string.h> line after the #include <stdio.h> line at the top of your file.
The <string.h> file offers the strcpy() function.
When using strcpy() , you first include the name of the character array and then the new value you want to assign. The strcpy() function automatically add the string terminator on the new string that is created:
And there you have it. Now you know how to declare strings in C.
To summarize:
- C does not have a built-in string function.
- To work with strings, you have to use character arrays.
- When creating character arrays, leave enough space for the longest string you'll want to store plus account for the string terminator that is included at the end of each string in C.
- Define the array and then assign each individual character element one at a time.
- OR define the array and initialize a value at the same time.
- When changing the value of the string, you can use the strcpy() function after you've included the <string.h> header file.
If you want to learn more about C, I've written a guide for beginners taking their first steps in the language.
It is based on the first couple of weeks of CS50's Introduction to Computer Science course and I explain some fundamental concepts and go over how the language works at a high level.
You can also watch the C Programming Tutorial for Beginners on freeCodeCamp's YouTube channel.
Thanks for reading and happy learning :)
Learning something new everyday and writing about it
If this article was helpful, tweet it .
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

IMAGES
VIDEO
COMMENTS
Assign content to string Assigns a new value to the string, replacing its current contents. (1) string Copies str. (2) substring Copies the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is string::npos ). (3) c-string
Two solutions: either copy the string: strcpy (a.name, "Markson"); or use a const char pointer instead of an array and then you can simply assign it: struct { const char *name; /* etc. */ }; a.name = "Markson"; Or use a non-const char pointer if you wish to modify the contents of "name" later:
Initialize a string with the Empty constant value to create a new String object whose string is of zero length. The string literal representation of a zero-length string is "". By initializing strings with the Empty value instead of null, you can reduce the chances of a NullReferenceException occurring.
Assigning a string to a variable is done with the variable name followed by an equal sign and the string: Example Get your own Python Server a = "Hello" print(a) Try it Yourself » Multiline Strings You can assign a multiline string to a variable by using three quotes: Example Get your own Python Server You can use three double quotes:
The member function assign () is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str. string& string::assign (const string& str) str : is the string to be assigned. Returns : *this CPP #include <iostream> #include <string> using namespace std;
Create a variable of type String and assign it a value: String greeting = "Hello"; Try it Yourself » String Length A String in Java is actually an object, which contain methods that can perform certain operations on strings. For example, the length of a string can be found with the length () method: Example Get your own Java Server
Strings are represented fundamentally as sequences of UTF-16 code units.In UTF-16 encoding, every code unit is exact 16 bits long. This means there are a maximum of 2 16, or 65536 possible characters representable as single UTF-16 code units.This character set is called the basic multilingual plane (BMP), and includes the most common characters like the Latin, Greek, Cyrillic alphabets, as ...
Giving a variable a value is often referred to as assigning a value to the variable. We'll create four string variables and one numeric variable, this_year: me=Dave my_boost=Linux him=Popeye his_boost=Spinach this_year=2019 To see the value held in a variable, use the echo command.
Python Assign String Variables SQL JAVA PHP Python String Variables Python Glossary Assign String to a Variable Assigning a string to a variable is done with the variable name followed by an equal sign and the string: Example Get your own Python Server a = "Hello" print(a) Try it Yourself » Python Glossary Report Error Spaces Upgrade
4 Ways to Initialize a String in C 1. Assigning a string literal without size: String literals can be assigned without size. Here, the name of the string str acts as a pointer because it is an array. char str [] = "GeeksforGeeks"; 2. Assigning a string literal with a predefined size: String literals can be assigned with a predefined size.
When you assign a variable of type string to another of type string, the value is copied. In this case, the value is a reference and it is copied by the assignment. This is true for any reference type, not just string or only immutable reference types.
std::basic_string<CharT,Traits,Allocator>::assign From cppreference.com < cpp | string | basic string C++ Compiler support Freestanding and hosted Language Standard library Standard library headers Named requirements Feature test macros (C++20) Language support library Concepts library(C++20) Metaprogramming library(C++11) Diagnostics library
In JavaScript, you can choose single quotes or double quotes to wrap your strings in. Both of the following will work okay: const sgl = 'Single quotes.'; const dbl = "Double quotes"; console.log(sgl); console.log(dbl); Copy to Clipboard. There is very little difference between the two, and which you use is down to personal preference.
Assigning Values to Strings Arrays and strings are second-class citizens in C; they do not support the assignment operator once it is declared. For example, char c [100]; c = "C programming"; // Error! array type is not assignable. Note: Use the strcpy () function to copy the string instead. Read String from the user
There are two ways to create a string in Java: String Literal Using new Keyword String literal String s = "GeeksforGeeks"; Using new keyword String s = new String ("GeeksforGeeks"); StringBuffer is a peer class of String that provides much of the functionality of strings.
The String data type represents a series of characters (each representing in turn an instance of the Char data type). This topic introduces the basic concepts of strings in Visual Basic. String Variables An instance of a string can be assigned a literal value that represents a series of characters. For example: VB
Assigns a new value to the string, replacing its current contents. (See member function assign for additional assignment options). Parameters str A string object, whose value is either copied (1) or moved (5) if different from *this (if moved, str is left in an unspecified but valid state). s Pointer to a null-terminated sequence of characters.
Well, strings in C are actually a type of array - specifically, they are a character array. Strings are a collection of char values. How strings work in C. In C, all strings end in a 0. That 0 lets C know where a string ends. That string-terminating zero is called a string terminator.