C++ String class string segmentation implementation

  • 2020-05-26 09:48:20
  • OfStack

C++ String class string segmentation implementation

For functional requirements, enter a string "1-2-3" and cut out "1", "2" and "3". Just use the split function of String under Java. c++ String does not provide this function directly, so you need to write it yourself.

The solutions given on the web are the three methods here. However, I accessed it through JNI, in which I may not be able to use these vector, but encapsulate one by myself, just for reference:


String recogScop = "01-02-03"; 
cout<<recogScop<<endl; 
int size = recogScop.size(); 
int pos = 0; 
string result[20] ; 
 
for(int i=0, j=0; i<size; i++,j++ ) 
{ 
  pos = recogScop.find("-", i); 
 
  if(pos == -1) 
  { 
    String subEnd = recogScop.substr(i, size - i); // The last 1 A string  
    result[j] = subEnd; 
    break; 
  } 
  if(pos >0) 
  { 
    String sub = recogScop.substr(i, pos-i); 
    result[j] = sub; 
    i = pos; 
  } 
} 
 
for(int i=0; result[i] != ""; i++) 
  cout<<result[i]<<endl;  

Note: the above find result pos is greater than 0, indicating that the "-" delimiter can be found. If this fails, the last delimiter, pos will be equal to negative 1.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: