• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 241
  • Last Modified:

Creating a copy of the string, up to an index position

Hi,

If I have a string ("12324345323") and an index value (5), how would I use C++ to copy the string up to the 6th position?

I want to see ("123243")

Thanks.
0
ba272
Asked:
ba272
  • 3
  • 2
2 Solutions
 
AxterCommented:
The substr member function returns a string type.

string MyString("12324345323");

string SubString = MyString.substr(0, 6);
0
 
hongjunCommented:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( void )
  {
    char buffer[15];

    strncpy(buffer, "12324345323", 6);
    buffer[6] = '\0';
    printf( "%s\n" buffer);

    return EXIT_SUCCESS;
  }
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
AxterCommented:
substr has the following signature type:
basic_string substr(size_type pos = 0,
    size_type n = npos) const;

It returns a string type, and you can use it to pull sections of your existing string.
0
 
AxterCommented:
FYI:
Even with a C-Style string, it's easier to pull a sub section using std::string.
Example:
 char buffer[15] =  "12324345323";
 string SubData(buffer, buffer+6);
 cout << SubData << endl;
0
 
ba272Author Commented:
I do prefer strnpy() when writing C++ actually.  substr() when using C#.

Thanks.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now