Common methods of string in C + +

Time:2021-4-20

String string is very important in all languages, C ++ It’s no exception , Next, we will introduce the common methods in string

1. Size() and length() functions: they return the real length of the string and will not be truncated because of the space. These two methods are completely equivalent. The use and output are as follows:

#include<iostream>
#include<string>
using namespace std;
 
int main(void)
{
  string s = "dasddasd";
  Printf ("length returned by size():% Lu, length returned by nlength():% Lu", s.size(), s.length());
  return 0;
}

2. Find() function and rfind() function: these two functions are used to find the position of the string in the parent string, and return the position. Of course, if not, a special tag will be returnedstring::nops, the find() function searches backward from the start pointer of the string, and the rfind() function searches forward from the end pointer of the string. Its use and output are as follows:

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

int main(void)
{
  string s = "hello worldh";
  Int index = s.find ("H"); // search backward from the beginning of the string
  int index2  =  s . find (" h ", two )  //  The position of the substring in the parent string after the fixed position
  Int index1 = s.rfind ("H"); // look forward from the end of the string
  printf ("( find ()): The position of the letter H in the parent string is :% d \ n ",  index ); 
  Printf ("(rfind()): the position of the letter H in the parent string is% d", index1);
  return 0;
}

It is worth noting that we can judge whether the substring exists only in the parent string by combining these two functions. The implementation code is as follows:


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

inline bool whetherOnly(string &str,string &base){
  return base.find(str) == base.rfind(str); 
}

3. find_last_of()Function sumfind_first_of()Function: we can also know from the function namefind_last_of()Function is to find the last position of the substring in the parent string and return the positionfind_first_of()Function is to find the last position of the substring in the parent string and return the position. Its use and output are as follows :

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

int main(void)
{
  string s = "hello worldh";
 
  int index = s.find_first_of("h");
  int index1 = s.find_last_of("h");
  printf ("( find_ first_ of ()): The position of the letter H in the parent string is :% d \ n ",  index );
  printf("(find_ last_ Of ()): the position of the letter H in the parent string is% d ", index1);
}

four . assign () Function: this function is used to copy the value of the target string to the string, and only copy the value. Its use and output are as follows:


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

int main(void)
{
  string s = "hello worldh";
  s.clear();
  s.assign("hello world");
  cout<<s<<endl;
  
}

5. Clear() function to clear the current string. If you callstring::size()Function orstring::length()The function will return 0. Its use and output are as follows:

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

int main(void)
{
  string s = "hello worldh";
  s.clear();
  Cout < "length of string after clear" < < s.size() < < endl;
}

6. Resize() function, which can lengthen the string to the specified length. If it is less than the length of the original string, the original string will be truncated. An overloaded form of this function isstr.resize(length,'s')The input character’s’ can be used to expand the string to length. The use and output of this function are as follows:

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

int main(void)
{
  string s = "hello worldh";
  s. Reset (5); // s will become hello
  cout<<s<<endl;
  s. Reset (10, 'C'); // s will become helloccccc
  cout<<s<<endl;
  
}

7. replace(pos,len,dist)Function: this function is used to replace the string from POS position to dist string. It is worth noting that this function is only replaced once, which is different from py and Java on the market. It should be noted that the use and output of this function are as follows:

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

int main(void)
{
  string s = "hello worldh";
  s. Replace (s.find ("H"), 2, "#); // change two characters from the first h into one character#
  Cout < "the replaced string is: < < s < < endl;
  
}

So since c ++ It does not provide a function to replace all substrings. We will implement one by ourselves. The code is as follows :

//Replaces all specified characters in the string
String replace (string & base, string SRC, string DST) // base is the original string, SRC is the substring to be replaced, DST is the new substring
{
  int pos = 0, srclen = src.size(), dstlen = dst.size();
  while ((pos = base.find(src, pos)) != string::npos) 
  {
    base.replace(pos, srclen, dst);
    pos += dstlen;
  }
  return base;
}

8. erase(index,length)Function: this function deletes the length substring after the index position. Its code and output are as follows:

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

int main(void)
{
  string s = "hello worldh";
  s.erase(s.find("h"),3);
  Cout < < s < < endl; // output lo worldh
}

nine . substr ( index , length ) function : The function truncates from index to length and returns the truncated substring; It is worth noting that this function does not change the value of the parent string. Its use and output are as follows :

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

int main(void)
{
  s = s.substr(0,5); 
  Cout < "truncated and assigned string is: < < s < < endl; // output Hello
}

ten . push_ back ( char c ) Function, pop_ back () Function, append ( string s ) Function: push_ back ( char c ) Function to add a character to the end of the string ; pop_ back () Function pops a character from the end of the string ; Apend ( string s ) The function adds a string to the end of the string and returns a reference to the added string. Their use and output are shown in the figure below :

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

int main(void)
{
  string s = "hello worldh";
  // s.erase(s.find("h"),3);
  s.pop_ Back(); // pop up the last element of the string
  Cout < "the string after the pop-up string end element is: < < s < < endl;
  s . push_ back (' s '); //  Add a character at the end of the string
  cout <<" The string after adding characters to the end of the string is : "<< s << endl ;
  s. Append ("HHH"); // add a string at the end of the string
  Cout < "the string added to the end of the string is: < < s < < endl;
}

The above is the whole content of the more important functions in string. Now that we have learned this content, let’s do a question to familiarize ourselves with some of these functions (the title and code are as follows, the title comes from leetcode)

//Here's a vocabulary (string array) words and an alphabet (string) chars.
//If you can spell a word (string) in words with the letter (character) in chars, then we think you have mastered the word.

//  Note: each letter in chars can only be spelled once.
//  Returns the sum of the lengths of all the words in the vocabulary.

//Input: words = ["cat", "BT", "hat", "tree"], chars = "atach"
//Output: 6
//  Explanation:
//The strings "cat" and "hat" can be formed, so the answer is 3 + 3 = 6.

//Input: words = ["hello", "world", "leetcode"], chars = "welldone honeyr"
//Output: 10
//  Explanation:
//The string "hello" and "world" can be formed, so the answer is 5 + 5 = 10.

#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution
{
public:
  int countCharacters(vector<string> &words, string chars)
  {
    int count = 0;
    Bool flag = false; // flag
    string c_ Chars (chars); // construct C_ Chars save chars
    for (int i = 0; i <  words.size (); I + +) // iterate word list
    {
      if  ( c_ chars . size () <  words [ i ]. size ()) // If the word has more letters than optional, skip the word
        continue;
      For (int j = 0; J < words [i]. Size(); j + +) // iterate with optional letters
      {
        int index = c_chars.find(words[i][j]);
        if (index != c_ chars.npos )// you can find this letter
        {
          flag = true;
          c_ chars.erase (index, 1); // from C_ Chars () removes the letter
        }
        else
        {
          flag  =  false ; //  Can't find it , It means it can't make up the word
          Break; // jump out of this loop
        }
      }
      If (flag) // if it matches, add 1 to the count
        count += words[i].size();
      c_ chars.assign (chars); // assign the value of chars to C again_ chars
    }
    return count;
  }
};

Finally, thank you for reading. The combination of these functions in string can be said to be extremely powerful, so we still need to master them well.

summary

This article about the use of string method in C + + is introduced here. For more information about the use of string method in C + +, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!

Recommended Today

Quickly use the latest 15 common APIs of vue3

Before that, I wrote a blog to introduce the new features of vue3. I had a brief understanding of the features of vue3, and at the end of the article, I gave you a little experience in vue3Compsition APISimple use of Address of last article: follow Youda’s steps and experience the new features of vue3 […]