In C++, a string is a sequence of characters used to represent text. Strings are an essential part of programming as they allow us to work with textual data efficiently. Whether you’re dealing with user inputs, file manipulation, or any other text-based operations, understanding how to use strings in C++ is crucial.
Declaration,access and initialization of String in C++
A string is defined as an array of characterswith additional predefined methods support through headers
std::string ="value";
ex:
std::string name ="trishaank";//direct declaration and initialization
cout<<name;//directly access by string name
Advantages of Using Strings in C++:
Easy Manipulation: C++ strings provide a wide range of built-in functions that make it easy to manipulate and process textual data. Concatenation, searching, replacing, and other common string operations can be performed efficiently.
Dynamic Size:Unlike character arrays, C++ strings have a dynamic size. This means you don't need to worry about allocating an exact amount of memory for your string, as it can grow or shrink as needed.
Safer Operations: C++ strings handle memory allocation and deallocation automatically, reducing the risk of buffer overflow or memory leaks, which are common issues when working with character arrays.
#include <iostream>
using namespace std;
int main()
{
string name; name = "My name is 3shaank";
cout << name.length() <<endl;//includes whitespaces also
return 0;
}
#include <iostream>
using namespace std;
int main()
{
string s = "I hate my college";
s.clear();//string became empty
cout << "Value of s is :" << s << endl;
cout<<"size of s"<<s.length();// 0 because empty
return 0;
}
Login/Signup to comment