Skip to main content

string

Errors

❌ string size() gives WRONG answer when compared with -ve values ❌

.size is an unsigned int, the regular -ve int is automatically converted to unsigned.

Store str.size() in a variable of int data type and this should solve your problem.


Taking String as Line

String str;
getline(cin, str);

string Methods

Element access

at()


front()


back()



Operations

push_back()

caution

string don't have -> emplace_back() because there will be no gain over push_back()

push_back() in Strings is more efficient than concatenation ~ str + 'ing' . as push_back() is O(1) and str + 'ing' is O(size of String)


contains() C++ 23



pop_back()


append()


insert()


replace()


substr()

info

https://en.cppreference.com/w/cpp/string/basic_string/substr

  • Parameters
    • index also called pos: position of the first character to include
    • count: length of the substring
string str = "Hello World this!";

string str1 = str.substr(3); // str.substr(3, size())

string str1 = str.substr(3, 7); // str.substr(3, 10) /* here 10 is included */
// str1 is from index '3' to '3+7' index

string sub3 = str.substr(str.size()-3, 50); // pos is within bounds, pos+count is not, returns [pos, size())

copy()


resize()


swap()


clear()


erase()

caution

str.erase(iteratior) takes iterator as parameter type like: str.erase(str.begin() + 3) or `str.erase(remove())

info
  • Remove a particualar character from a string 👇
str.erase(str.begin() + x);
// "x" is the IndexNo. of that particular character

Taking iterator from remove()

    str.erase(remove(str.begin(), str.end(), ' '), str.end());

erase_if()


find()

info

To check where a string contains a substring

if substring is found then str.find() returns the opening index , else if substring not found then str.find() returns -1;

string str ("There are two needles in this haystack.");
string str2 ("needle");

if (str.find(str2) != string::npos) { // returns "true" or "false"
cout << "Yes, Found! that means it 'str' contains the substring 'str2' "
}

starts_with()


ends_with()


Number to String

to_string()

int x;
cin >> x; // 01213

string str = to_string(x);
cout << "String is " << str << endl;

/* Output ⇣
String is 1213
*/

to_wstring()

Not Needed


String to Number

stoi(), stoll, stol, stoull, stoul

caution
  • stoi() is for int
  • stoll() is for long long
  • stol() is for long
  • stoull() is for unsigned long long
  • stoul() is for unsigned long

String to Decimal:

  • stof() is for float
  • stod() is for double
  • stold() is for long double

Also: atoi() is an alternative of stoi() but MUST not be used.`

Also Refer: https://en.cppreference.com/w/cpp/utility/from_chars

string str;
cin >> str;

int conv = stoi(str);

cout << "converted string tp num is: " << conv << endl;

using stringstream()

    string str;
cin >> str;

istringstream iss(str);

int num;
iss >> num;

cout << "converted string tp num is: " << num << endl;

to_integer()

Facing Problems with it.


char to integer

// `s.at(i)` is a character of  string "s"

int x = s.at(i) - '0'

Basic string PROBLEMS

Conversion of whole String to uppercase or lowercase

  • ::lowercase
string s = "AbCdE fGhIj";
transform(s.begin(), s.end(), s.begin(), ::tolower);

// 'str' becomes "abcde fghij"
  • ::uppercase
string str = "AbCdE fGhIj";
transform(s.begin(), s.end(), s.begin(), ::toupper);

// 'str' becomes "ABCDE FGHIJ"

stringName.erase(unique(stringName.begin(), stringName.end()), end());

// Input is:  "helloWoroldd"
string s;
cin >> s;
transform(s.begin(), s.end(), s.begin(), ::tolower);

sort(s.begin(), s.end()); // s = "ddloroWolleH"

s.erase(unique(s.begin(), s.end()), s.end()); // 👉 removes all the diplicate elements except "first occurance of the element"
//👆 Here, "unique(s.begin(), s.end())" ⏩ , string "s" becomes "dehlorw*****"
//👆 Here, "s.end()" is used after 'unique()' inside "erase()" ⏩ because , all unknowns "*" gets removed and 'only last iteratorof the VALID string' "s" becomes -> "dehlorw"


cout << s; // 👉 Prints "dehlorw"
  • Here, "unique(s.begin(), s.end())" ⏩ , string "s" becomes "`dehlorw***"** Here, "s.end()" is used after 'unique()' inside "erase()" ⏩ because , all unknowns "*`" gets removed and 'only last iteratorof the VALID string' "s" becomes ⇒ "dehlorw"

Finding Frequency of charaters in a string

info

count() - number of occurances / frequency

cout << count(str.begin(), str.end(), targetCharacter);

> **counts the number of occurances of that element.**
> Refer: https://en.cppreference.com/w/cpp/algorithm/count

---

Using unordered_map


  • Use HashMap to add all the elements to a Key and then print only those elements occur once. This Method will sort the elements

Remove spaces from string

info

using remove()

using reverse() to get itetors for the range of spaces in the string and then using erase() to get those iterators from remove() and use it to point to the first iterator [similar to begin() + ..].

string str;
getline(cin, str); // "Hello World Axyz"

str.erase(remove(str.begin(), str.end(), ' '), str.end());

cout << str << endl; // "HelloWorldAxyz"

using remove() as


using <regex> Header's ~ regex_replace()

string str;    // Hello    World
getline(cin, str);

regex r("\\s+"); // "\\s+" consists of all white spaces 'tabs' or ' ' or ' '
str = regex_replace(str, r, ""); //👉 replaces all "\\s+" with "" (no space)

cout << str << endl; //prints "HelloWorld"

string str;
getline(cin, str); // "Hello World Axyz"

for (int i = 0; i < str.size(); i++)
{
if (str.at(i) == ' ')
{
str.erase(str.begin() + i);
}
}

cout << str << endl; // "HelloWorldAxyz"

More ways


Removing Duplicates in string order as given

info

using erase() and unique() till end() iterator of unique()

string str;
getline(cin, str);

str.erase(unique(str.begin(), str.end()), str.end());

cout << str << endl;

string str;
getline(cin, str);

for (int i = 1; i < str.size(); i++)
{
if (str.at(i) == str.at(i - 1))
{
str.erase(str.begin() + i);
i--;
}
}

cout << str << endl;

  • using recursion
#include <bits/stdc++.h>
using namespace std;

#define ll long
#define endl "\n"

void sol(string &s, ll i, ll len)
{
// base case
if (i == len)
{
return;
}
else if (i < len)
{
if (s.at(i) == s.at(i - 1))
{
s.erase(s.begin() + i);
i--;
}
}
sol(s, i + 1, s.size()); // recursive case , Here "s.size()" becomes the length which helps in "base case"
}

int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);

string str;
getline(cin, str);

sol(str, 1, str.size());

cout << str << endl;

return 0;
}

Copied from GeeksforGeeks

  • using unordered_map -- O(n) , Space = O(n)
// C++ program too create a unique string using unordered_map

/* access time in unordered_map on is O(1) generally if no collisions occur
and therefore it helps us check if an element exists in a string in O(1)
time complexity with constant space. */

#include <bits/stdc++.h>
using namespace std;
char* removeDuplicates(char *s,int n){
unordered_map<char,int> exists;
int index = 0;
for(int i=0;i<n;i++){
if(exists[s[i]]==0)
{
s[index++] = s[i];
exists[s[i]]++;
}
}
return s;
}

//driver code
int main(){
char s[] = "geeksforgeeks";
int n = sizeof(s)/sizeof(s[0]);
cout<<removeDuplicates(s,n)<<endl;
return 0;
}



Null-terminated byte strings cctype

  • It is only for changing char values inside string

isalnum

  • checks if a character is alphanumeric

isalpha

  • checks if a character is alphabetic

islower

  • checks if a character is lowercase

isupper

  • checks if a character is an uppercase character

isdigit

  • checks if a character is a digit

    Returns: Non-zero value if the character is a numeric character, 0 otherwise.

if (isdigit(charName)) {

/* code */
}
if ( isdigit(str[i]) ) {

/* code */
}

isxdigit

  • checks if a character is a hexadecimal character

iscntrl

  • checks if a character is a control character

isgraph

  • checks if a character is a graphical character

isspace

  • checks if a character is a space character

isblank


checks if a character is a blank character (function)

isprint

  • checks if a character is a printing character

ispunct

  • checks if a character is a punctuation character

Character manipulation

tolower

  • converts a character to lowercase

toupper


  • converts a character to uppercase

Strings Topic List

Strings Topics
String Algorithms
String Adhocs (frequency count, ciphering.. etc)
String Hashing
Manacher's Algorithm (Counting Palindromes)
String Matching
Prefix Function (KMP), Prefix Automaton
Z Algorithm
Aho Corasick
DP: String Alignment and LCS
Suffix Structures
Suffix Trie and Tree
Suffix Array
Suffix Automaton