{"id":81409,"date":"2021-07-07T09:00:59","date_gmt":"2021-07-07T03:30:59","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=81409"},"modified":"2021-07-07T09:00:59","modified_gmt":"2021-07-07T03:30:59","slug":"strings-in-cpp","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/","title":{"rendered":"Strings in C++"},"content":{"rendered":"<p>We will learn how to work with strings in C++ in this article.<\/p>\n<p>A string stores a sequence of characters. In C++, there are two types of strings:<\/p>\n<p>1. C-style strings<br \/>\n2. Objects of the string class in the Standard C++ Library<\/p>\n<h3>C-style Strings<\/h3>\n<p>C++ continues to support C-style strings. Arrays are used to store a group of characters in C programming. C-style strings are 1-D char arrays with a null character \u2018\\0\u2019 at the end.<\/p>\n<h4>1. Defining a C-style string<\/h4>\n<p><strong>Syntax to declare a string:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">char string_name[size];<\/pre>\n<p>Let\u2019s initialize string str to store the word TechVidvan. This can be done in the following ways:<\/p>\n<ul>\n<li>char str[] = &#8220;TechVidvan&#8221;;<\/li>\n<li>char str[20] = &#8220;TechVidvan&#8221;;<\/li>\n<li>char str[] = {\u2018T\u2019, \u2018e\u2019, \u2018c\u2019, \u2018h\u2019, \u2018V\u2019, \u2018i\u2019, \u2018d\u2019, \u2018v\u2019, \u2018a\u2019, \u2018n\u2019, \u2018\\0\u2019};<\/li>\n<li>char str[11] = {\u2018T\u2019, \u2018e\u2019, \u2018c\u2019, \u2018h\u2019, \u2018V\u2019, \u2018i\u2019, \u2018d\u2019, \u2018v\u2019, \u2018a\u2019, \u2018n\u2019, \u2018\\0\u2019};<\/li>\n<\/ul>\n<p><strong>Example to read and display C-style string<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nint main() {\n  char word[20];\n  char line[100];\n  \n  \/\/read a word\n  cout&lt;&lt;\"Enter a word \";\n  cin&gt;&gt;word;\n  \/\/display the word\n  cout&lt;&lt;endl&lt;&lt;word&lt;&lt;endl;\n  \n  \/\/read a line \n  cout&lt;&lt;\"Enter a line \";\n  cin.get(line, 100);\n  \/\/display the line\n  cout&lt;&lt;endl&lt;&lt;line;\n  \n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Enter a word TechVidvan<br \/>\nTechVidvan<br \/>\nEnter a line Articles on C++ programming<br \/>\nArticles on C++ programming<\/div>\n<p>Here, to read a line we used <strong>cin.get()<\/strong> function. It is used to read character arrays including whitespaces.<br \/>\n<strong>Syntax<\/strong>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">cin.get(string_name, size);<\/pre>\n<h3>Object of std::string C++ class<\/h3>\n<p>In C++, we can represent strings as objects of std::string class. These objects are used to hold strings. The string class holds characters as a stream of bytes where we can access a single byte character.<\/p>\n<p>Unlike character arrays, string objects do not have a fixed length and can be increased as needed.<\/p>\n<p>Remember that to use string, we must include the &lt;string&gt; library as a header file in our code.<\/p>\n<h4>1. Defining a string object<\/h4>\n<p><strong>Syntax to declare a string object:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">string string_name;<\/pre>\n<p>Let\u2019s initialize a string object,<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">string str = \"TechVidvan\";<\/pre>\n<p><strong>Example to illustrate the use of string<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\n#include &lt;string&gt;\nusing namespace std;\n\nint main() {\n  string s1;\n  \n  \/\/taking input of a string from user\n  getline(cin, s1);\n  \n  \/\/displaying the string\n  cout&lt;&lt;\"Entered string is \"&lt;&lt;s1;\n  return 0;\n}\n<\/pre>\n<p><strong>Input<\/strong><br \/>\nTechVidvan<br \/>\n<strong>Output<\/strong><\/p>\n<div class=\"code-output\">Entered string is TechVidvan<\/div>\n<p>In the above example, we have used the <strong>getline()<\/strong> function to store the string entered by the user.<\/p>\n<p>Some other functions to operate on strings<\/p>\n<p><strong>1. push_back() :<\/strong> We use this function to add a character at the end of a string.<br \/>\nSyntax:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">string_name.push_back(\u2018character\u2019);<\/pre>\n<p><strong>2. pop_back() :<\/strong> We use this function to delete the last character of a string.<br \/>\nSyntax:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">string_name.pop_back();<\/pre>\n<p><strong>3. length() and size() :<\/strong> We use these functions to get the length of a string.<br \/>\nSyntax:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">string_name.length();<\/pre>\n<p>Or<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">string_name.size();<\/pre>\n<h3>Memory occupied by strings in C++<\/h3>\n<p>We know that data type char occupies 1 byte of memory space. A string in C++ thus occupies N bytes where, N = no. of characters in a string including the null character.<\/p>\n<p>For example,<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">char s[ ] = \"TechVidvan\";<\/pre>\n<p>This string s will occupy (10 + 1) = 11 bytes of memory space. We can represent this in tabular form as shown below<\/p>\n<p>While designing, instead of DATAFLAIR\\0, it will be TECHVIDVAN\\0 and index from 0 &#8211; 10.<\/p>\n<p>We can use sizeof() operator to get the size of a string.<\/p>\n<h3>C++ Functions for strings<\/h3>\n<p>C++ offers various functions to operate on strings.<\/p>\n<p>1. <strong>strcpy<\/strong>(string1, string2); : We use this function to copy string2 into string1.<\/p>\n<p>2.<strong> strcat<\/strong>(string1, string2); : We use this function to concatenate both the strings.<\/p>\n<p>3.<strong> strlen<\/strong>(string1); : We use this function to compute the length of a string.<\/p>\n<p>4. <strong>strcmp<\/strong>(string1, string2); : We use this function to compare both the strings. It returns 0 when both are equal, &lt;0 when string1&lt;string2 and &gt;0 when string1&gt;string2.<\/p>\n<p>5. <strong>strchr<\/strong>(string1, ch); : We use this function to get the pointer pointing to the first appearance of character ch in a string.<\/p>\n<p>6.<strong> strrchr<\/strong>(string1, ch); : We use this function to get the pointer pointing to the last appearance of character ch in a string.<\/p>\n<p>7. <strong>strstr<\/strong>(string1, string2); : We use this function to get the pointer pointing to the first appearance of string2 in string1.<\/p>\n<p>8.<strong> strlwr<\/strong>(string1); : We use this function to convert all the characters of a string to lowercase.<\/p>\n<p>9.<strong> strupr<\/strong>(string1); : We use this function to convert all the characters of a string to uppercase.<\/p>\n<p>10. <strong>strncat<\/strong>(string1, string2, n); : We use this function to append first n characters of string2 at the end of string1.<\/p>\n<p>11. <strong>strncpy<\/strong>(string1, string2, n); : We use this function to copy first n characters of string2 into string1.<\/p>\n<p>12.<strong>strncmp<\/strong>(string1, string2, n); : We use this function to compare n characters of both the strings. It returns 0 when both are equal, &lt;0 when\u00a0 string1&lt;string2 and &gt;0 when string1&gt;string2.<\/p>\n<p>13. <strong>strcmpi<\/strong>(string1, string2); : We use this function to compare both the strings without considering case sensitivity. It returns 0 when both are equal, &lt;0 when string1&lt;string2 and &gt;0 when string1&gt;string2.<\/p>\n<p>14.<strong> strnicmp<\/strong>(string1, string2, n); : We use this function to compare n characters of both the strings ignoring case sensitivity. It returns 0 when both are equal, &lt;0 when string1&lt;string2 and &gt;0 when string1&gt;string2.<\/p>\n<p>15.<strong> strdup<\/strong>(string1); : We use this function to get a pointer to a duplicate string of string1.<\/p>\n<p>16.<strong> strndup<\/strong>(string1, n); : This function works similar to strdup except, it duplicates n characters of string.<\/p>\n<p>17.<strong> strset<\/strong>(string1, ch); : We use this function to set all characters of a string to character ch.<\/p>\n<p>18. <strong>strnset<\/strong>(string1, ch, n); : We use this function to set first n characters of a string to character ch.<\/p>\n<p>To use these functions we need to include &lt;string.h&gt; header file in our program.<\/p>\n<p><strong>Example to illustrate the use of some C++ string functions<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\n#include &lt;string.h&gt;\nusing namespace std;\n\nint main() {\n  char s1[ ] = \"TechVidvan\";\n  char s2[ ] = \"DataFlair\";\n  \n  int length = strlen(s1);\n  cout&lt;&lt;\"Length of string TechVidvan = \"&lt;&lt;length&lt;&lt;endl;\n  \n  char s3[15];\n  strcpy(s3, s1);\n  cout&lt;&lt;\"Copied string = \"&lt;&lt;s3&lt;&lt;endl;\n  \n  strcat(s1,s2);\n  cout&lt;&lt;\"Concatenated strings = \"&lt;&lt;s1&lt;&lt;endl;\n  \n  if(strcmp(s1,s2)==0)\n      cout&lt;&lt;\"Strings are equal\";\n  else\n      cout&lt;&lt;\"Strings are unequal\";\n  \n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Length of string TechVidvan = 10<br \/>\nCopied string = TechVidvan<br \/>\nConcatenated strings = TechVidvanDataFlair<br \/>\nStrings are unequal<\/div>\n<h3>Passing string to a function<\/h3>\n<p><strong>Example of strings as function parameters<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\n#include &lt;string&gt;\nusing namespace std;\n\nvoid print(char s[], string str) {\n    cout&lt;&lt;\"Entered C-style string is \"&lt;&lt;s&lt;&lt;endl;\n    cout&lt;&lt;\"Entered string object is \"&lt;&lt;str;\n}\nint main() {\n  char s1[50] = \"TechVidvan\";\n  string s2 = \"Data Flair\";\n  \n  print(s1, s2);\n  \n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Entered C-style string is TechVidvan<br \/>\nEntered string object is Data Flair<\/div>\n<h3>Summary<\/h3>\n<p>In this article, we have learnt about strings in C++. A string is a sequence of characters. C++ offers us two types of strings, one in the form of character arrays and other as objects of std::string class. We discussed how to work with both the types of strings.We also learnt to pass strings to a function using example programs.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We will learn how to work with strings in C++ in this article. A string stores a sequence of characters. In C++, there are two types of strings: 1. C-style strings 2. Objects of&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":81712,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3405],"tags":[3692,3693,3694,3695,3696],"class_list":["post-81409","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cpp","tag-c-style-strings","tag-c-functions-for-strings","tag-c-string-functions","tag-memory-occupied-by-strings-in-c","tag-strings-in-c"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Strings in C++ - TechVidvan<\/title>\n<meta name=\"description\" content=\"A string stores sequence of characters. Learn how to work with strings in C++ and various C++ string Functions with examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Strings in C++ - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"A string stores sequence of characters. Learn how to work with strings in C++ and various C++ string Functions with examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-07T03:30:59+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Strings-in-c.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Strings in C++ - TechVidvan","description":"A string stores sequence of characters. Learn how to work with strings in C++ and various C++ string Functions with examples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/","og_locale":"en_US","og_type":"article","og_title":"Strings in C++ - TechVidvan","og_description":"A string stores sequence of characters. Learn how to work with strings in C++ and various C++ string Functions with examples.","og_url":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-07-07T03:30:59+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Strings-in-c.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Strings in C++","datePublished":"2021-07-07T03:30:59+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/"},"wordCount":951,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Strings-in-c.jpg","keywords":["C-style Strings","C++ Functions for strings","C++ STring Functions","Memory occupied by strings in C++","Strings in C"],"articleSection":["C++ Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/","url":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/","name":"Strings in C++ - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Strings-in-c.jpg","datePublished":"2021-07-07T03:30:59+00:00","description":"A string stores sequence of characters. Learn how to work with strings in C++ and various C++ string Functions with examples.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Strings-in-c.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Strings-in-c.jpg","width":1200,"height":628,"caption":"Strings in c++"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/strings-in-cpp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Strings in C++"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81409","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=81409"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81409\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/81712"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=81409"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=81409"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=81409"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}