1

This is not homework, I need this for my program :)

I ask this question, because I searched for this in Google about 1 hour, and I don't find anything ready to run. I know that is trivial question, but if you will help me, you will make my day :)

Question:

How to copy text in string (from for example 8 letter to 12 letter) and send to other string?

I have string:

string s = "RunnersAreTheBestLovers";

and I want text from 8 letter to 17 letter in next string

Alice90

Alice90
  • 13
  • 2

5 Answers5

6

The string class has a substr method:

string t = s.substr(8, 9);

The first parameter is the starting index and the second parameter is the number of characters to extract.

Greg Hewgill
  • 890,778
  • 177
  • 1,125
  • 1,260
4

I assume you're trying to get the 8th - 17th characters in a another string. If so you should use the substring method string::substr

string s = "RunnersAreTheBestLovers";
string other = s.substr(8, 9);
Ben S
  • 67,195
  • 30
  • 170
  • 212
  • Thanks, I saw this function, but I though, that it accept only 1 argument :) – Alice90 Apr 14 '10 at 20:30
  • 1
    If you only use one argument, it will take the string from that character to the end. – Ben S Apr 14 '10 at 20:31
  • 1
    Note that the second argument to `substr()` is the *number* of characters to extract, not the *ending index* (this is different from some other languages such as Java). – Greg Hewgill Apr 14 '10 at 21:58
0

Check out the sections on copying and substrings:

http://www.cprogramming.com/tutorial/string.html

John
  • 15,934
  • 9
  • 67
  • 109
0

Take a look at the answers to this question.

Community
  • 1
  • 1
ubiquibacon
  • 10,105
  • 26
  • 107
  • 176
0


// For fun...  Assuming 8 and 17 are index values, could be off by 1
// Treat s and a char[], C style.

char *nextStringPtr = nextString; for(int i=8; i<17; i++) { *nextStringPtr++ = s[i]; } *nextStringPtr = 0;

Michael Dorgan
  • 12,285
  • 2
  • 29
  • 61