Strings In C/C++

Strings In C/C++
Strings In C/C++

Introduction

Strings in C/C++ can be defined as an array of characters terminated with null character ‘\0’.A string is used to store characters. C language does not have a string data type, it uses a character array instead. Sequential collection of char data type is called character array. A collection of characters represented as a single item is known as a string and it is terminated with a null character ‘\0’.

Suppose you want to store “Code Studio”.Now you have three options. The first one is that you can make a character variable to hold each character, that’s really a tedious job. The second one is that you can make a character array, and the last one is that you can store it in a string. In this blog, we’ll be mastering the third option.

Suppose we have a string “Code Studio.”Now let’s see how it’s stored internally in C/C++.

CodeStudio\0

So this is how strings in C/C++ are stored. Let’s see how to initialize a string using code in C/C++.Always remember that space is also considered a character in C/C++.

//one way is:-
//Take 1 extra size for string terminator
char str[12] = {‘C’, ‘o’, ‘d’, ‘e’, ‘ ‘ , ‘S’, ‘t’, ‘u’, ‘d’, ‘i’, ‘o’, ‘\0’ };

//other way is:-
char str[ ] = “Code Studio”;

Various manipulations can be done on strings in C/C++ using the functions provided in the in-built library. Let’s see them one by one in C first, and then we’ll be moving to functions provided by C++.

Strings in C

Suppose you are writing a C program and that you need to take the user name as an input by the user. Then how are you going to do it? Let’s see the solution to this problem:

You know scanf is used in C to take input, so we’ll be using this scanf to accomplish our task.

#include <stdio.h>

int main()
{
    //making a character array to store strings.
    char name[20];
    printf("Enter your name: ");

    //Taking user’s name as input from command line
    scanf("%s", name);

    //Printing user’s name
    printf("Hello  %s.", name);
    return 0;
}

So, in the above program, we learned to take a string as an input from the user, and we also learned to print a string as an output. That’s simple it is, isn’t it!

C string Functions

C language offers various in-built functions to manipulate strings. All these functions are present in the C standard library “ string. h”.

Let’s see some standard functions that will be very useful for you when you’re doing competitive programming.

blog banner 1

strlen()

Suppose you have a string in your program, and you want to calculate the length of the string. Then strlen() function is here for your help. It will give you the length of the string as output. Let’s understand it better with the below code:

#include <stdio.h>
#include <string.h>

int main()
{
    //making a character array to store strings.
    char name[20];
    printf("Enter your name: ");

    //Taking user’s name as input from command line
    scanf("%s", name);

    //Printing user’s name
    printf("Hello  %s.", name);

    //Printing length of username
   printf(“The length of your name is %zu”, strlen(name));
    return 0;
}

Now you must be wondering about %zu in the above code. We have used that because the strlen function returns the value as an unsigned integer type. Another thing you should never forget is that the strlen function never counts null characters in length.strlen() function counts the length by  traversing a string until a null character i.e ‘/0’ is found.

strcmp()

Suppose you are making a C program where you want to check if two strings are identical or not. Then you can use the strcmp() function to accomplish this task. This function is present in the string.h header file. 

strcmp() compares string by comparing each character. It converts each character to its ASCII code and then makes the comparison between ASCII codes of characters.

It will return 0 as output if both strings are equal, and it will return a non-zero integer if both the strings are not identical. Let’s discuss more about the working of strcmp().

strcmp() does comparison solely based on ASCII codes. Suppose you have two strings. Then we have three cases in it:-

Case 1. Each character is the same in both the strings.Then strcmp() will return 0 as output.

Case 2. The first non-matching character in one string has ASCII code greater than the one in another string, then we will receive an integer output greater than 0.

Case 3. The last case is that if the first non-matching character in the first string is lower than the character in the second string, we will receive an integer less than 0 as output. 

#include <stdio.h>
#include <string.h>

int main() {

   //Initializing two strings
  char str1[] = "CodingNinja", str2[] = "Codes";
  //In this variable we will store output
  int output;

  // comparing strings str1 and str2
  result = strcmp(str1, str2);
  printf("strcmp(str1, str2) = %d\n", output);

   return 0;
}
Output: strcmp(str1, str2) = 1

Since “CodingNinja” and “Codes” are not identical strings. Hence we received a non-zero output as a result of this program.

Now let’s move towards strings in C++.

Strings in C++

In C++, we have two options to make a string. The first one is to initialize string as the character of arrays as we did above. The second option is that C++ provides us with a class named string, and we can make strings using objects of this class. Since we have mastered the first method above,let’s master the second way now:

string class

C++ provides a string class, and by making an object of this class, you can work with strings easily. Internally string class in C++ uses a character array to store string, and it handles null character termination, allocation, and memory management all by itself. Let’s understand it better with the help of the code below:

#include<iostream>
#include<string>
using namespace std;

int main() {

//making an object of string class
string str;

//storing the string 
str = “CodeStudio”;

//printing output to the screen
cout << str << endl;
return 0;
}
Output: CodeStudio

Here we made an object str of the string class, and then you can see how easy it became to use the string in C++.No need to worry about null termination and size of the string in C++ only because of this awesome string class.

C++ string Functions

C++ library offers many in-built functions to manipulate strings. Let’s have a look at all of them one by one:

strlen() and size()

Both of these functions return the length of the string. You can use any one of these.

string str = “Coding”
cout << str.length() << endl;
cout << str.size() << endl;
Output: 
6
6

Note: Spaces in a string accounts for a character. Hence they are counted in string length. The null character is not included in string length.

push_back() 

With this function, you can append a character to the end of your string in C++. In C++, strings are internally implemented using a structure somewhat the same as a vector, so you don’t need to worry about string size.

#include <iostream>
#include<cstring>
using namespace std;

int main() {

string name = "Codin";

//pushing a character 'g' to the end
name.push_back('g');

cout << name;
return 0;
}
Output: Coding

You can add as many characters as you want to your string using the push-back function in C++.C does not offer any such functionality. That’s why it is said that C++ has made working with strings super easy.

pop_back()

With the help of this inbuilt function in the C++ string library, you can remove the last character from a string very quickly.You will get it more clearly by seeing the below code:-

#include <iostream>
#include<cstring>
using namespace std;

int main() {

string name = "Codingg";

//removing the last character
name.pop_back();

cout << name;
return 0;
}
Output: Coding

So in the above code, we deleted the ‘g’ character using the pop_back() function quite easily.

Let’s discuss more functions available to manipulate strings in C++.

FunctionArgumentsDescriptionExample
strcpy()s1, s2Copies string s2 into string s1.string s1 = “Code”string s2 = “Ninja”strcpy(s1, s2);cout << s1;
Output: Ninja

strcat()s1, s2Appends string s2 at the end of string s1string s1 = “Code”;string s2 = “Ninja”;strcat(s1, s2);cout << s1;
Output: Code Ninja.
strlen()s1Returns length of string s1string s1 = “Coding”;int result = strlen(s1);cout << result;
Output: 6
strstr()s1, s2Returns the pointer pointing at the first occurrence of string s2 in string s1.string s1 = “CodingNinja”string s2 = “Ninja”char *p = strstr(s1, s2);cout << p;
Output: Ninja
strcmp()s1, s2Returns 0 if s1 and s2 are the same and returns a non-zero value if both are different.string s1 = “Code”string s2 = “Ninja”int result = strcmp(s1, s2);cout << result;
Output: -1
getline()s1This stores a stream of characters as entered by the user.string code;cin >> “Enter your name”;getline(cin, code);cout << code;
Input: NinjaOutput: Ninja
capacity()s1It returns the size allocated to the string.string s1 = “Coding”;int cap = s1.capacity();
Output: 6
begin()s1Returns an iterator pointing at the beginning of the string.string s1 = “Coding”;cout << *s1.begin();
Output: C
end()s1Returns iterator pointing at the end of the string.string s1 = “Coding”;string::iterator it = s1.end();cout << (*it-1);
Output: g;
swap()s1, s2It swaps the strings.string s1 = “Coding”string s2 = “Ninja”s1.swap(s2);cout << s1 << “  “;cout << s2;
Output: Ninja  Coding
strchr()s1, cReturns a pointer to the last occurrence of a character in a string.char c = ‘e’;char st[] = “Cod”;char* res = strchr(st, c);cout << res;
Output: Code
substr()s1It takes two values pos(0-Based indexed) and len as an argument and returns a newly constructed string where copying starts from pos and done till pos+len.string s1 = “Coding”string res = s1.substr(1, 4);cout << res;
Output: odin
erase()s1It removes the character from the string as specified.It takes two arguments: position(0-Based indexed) and length.string s1 = “Coding”s1.erase(1, 2);cout << s1;
Output: Cing
clear()s1It removes all the characters from a string.string s1 = “Coding”s1.clear();cout << s1;
Output: “ ” 
find() s1This function is used for finding a specified string. This returns the index of the first occurrence of the substring in the string. string s1 = “Coding”;cout << s1.find(“ding”);
Output: 2
replace()s1, s2It replaces the portion of the string specified by the starting index and spans the  characters provided in length with string s2. string s1 = “Coding”;string s2 = “Ninja”;//Replace 3 characters from 0th index by s2s1.replace(0, 3, s2);
Output: Ninjaing

In the above table, s1 refers to string1 and s2 refers to string2.

Frequently Asked Questions

What is a string with an example in C++?

String in C++ is a sequence of characters.C++ also offers a string class with the help of which you can store your string in an object.
Example: string str = “CodingNinja”

Can I make an object of string in C?

No, In C, you can store your string only as a character of an array. C language does not offer string class as C++ does.

Does strlen() function count null characters in length?

No, strlen does not count null character in the length of the string. It only counts characters of the string in length.

How can I append a character to a string in C++?

You can use the push_back() function in C++ to append a character to your string.

What is the difference between strlen() function and size() function in C++?

There is no difference between both of them. They both will return the length of the string as an output. C does not have a size() function. It only supports the strlen() function for strings.

Key Takeaways

In this blog, we learned about strings in C/C++. Here you learned that the C language stores string as an array of characters while C++ stores string as an object of string class as well as an array of characters. You mastered various in-built functions for string manipulation here like strlen, strcmp, and size().You also learned to manipulate string using push_back() and pop_back() in C++.Always take note that it is mandatory to append null character at the end of the string if you are considering string as an array of characters in your program, otherwise, you will get the unexpected result in your output. Always remember that Knowledge increases with 2x speed when you share. So with whom are you going to share this article next?

By: Deeksha Sharma