In C++, String is one of the most used class to represent a sequence of characters. String class is an instantiation of the basic_string class template that uses char as the character type.
Check out the below C++ string functionalities you must know:
1. Converting C++ String into C String:
With
c_str function, you can covert the C++ string into a C string i.e null-terminated sequence of characters. Check out the example about c_str below:
int main()
{
std::string str("Hello");
char buf[10];
strcpy(buf, str.c_str());
std::cout<<buf<<std::endl;
return 0;
}
2. Knowing Length of String:
There are two functions to know the length of a string -
size() and
length()
Check out the example about size and length functions below:
int main()
{
std::string str("My Length")
std::cout<<str.size()<<" "<<str.length()<<std::endl;
/* will output 9 in both cases */
return 0;
}
3. Clearing a String:
clear() function will erase all the content of the string and makes it empty.
int main()
{
std::string str("Testing Clear Function");
str.clear();
return 0;
}
4. Check whether String is Empty or Not:
For this case, you can use
empty() function of string class.
void func(string str)
{
if (str.empty())
return;
}
5. Know String value at Specific Position:
If you want to get the value at specific position of a string, you can use
operator[] or
at() function
void func()
{
std::string str("0123456789");
std::cout<<str[5]; //will print 5
std::cout<<str.at(0); //will print 0
}
6.Appending a string:
To append a string to other string you can use
operator+= or
append() function.
void func()
{
std::string str("stacknow");
std::string str2("com");
str += ".";
str += str2;
/* str will be stacknow.com */
}
7.Erasing Few characters in string:
To erase a few characters in the string you can use
erase() function.
void func()
{
std::string str ("I LOVE YOU");
str.erase (1,5); /* will erase from 1st character and 5 characters length */
std::cout << str << '\n';
/* output will be "I YOU" */
}
8.Searching a sequence in string:
You can use
find() function for searching a sequence inside a string.
void func()
{
std::string str1 ("I am reading in stacknow.com");
std::size_t found = str.find("reading");
std::cout<< found << std::endl;
/* found will be 5, the first occurence value */
}
For more C++ string functions, you can visit
HERE.
yash
Wednesday, March 19, 2014
Related Posts