Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a part of the a string in C++?

Tags:

c++

How do I get a part of a string in C++? I want to know what are the elements from 0 to i.

like image 596
small_potato Avatar asked Mar 23 '10 07:03

small_potato


People also ask

How do you get a certain part of a string C?

strncpy() Function to Get a Substring in C The strncpy() function is the same as strcpy() function. The only difference is that the strncpy() function copies the given number of characters from the source string to the destination string.

How do I get only part of a string?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string.

How can I copy just a portion of a string in C?

strcpy can be used to copy one string to another. Remember that C strings are character arrays. You must pass character array, or pointer to character array to this function where string will be copied. The destination character array is the first parameter to strcpy .

Can you slice a string in C?

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.


1 Answers

You want to use std::string::substr. Here's an example, shamelessly copied from http://www.cplusplus.com/reference/string/string/substr/

// string::substr
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str="We think in generalities, but we live in details.";
                             // quoting Alfred N. Whitehead
  string str2, str3;
  size_t pos;

  str2 = str.substr (12,12); // "generalities"

  pos = str.find("live");    // position of "live" in str
  str3 = str.substr (pos);   // get from "live" to the end

  cout << str2 << ' ' << str3 << endl;

  return 0;
}
like image 67
Will Avatar answered Oct 16 '22 12:10

Will