简体   繁体   中英

Convert an array of character to string from index i to j in c++

I have an array of chars in c++.for example :

char input[]="I love you";

I want to make a std::string from char[i] to char[j]. for example :

std::string output="love";

What should i do?

You can do this:

char input[]="I love you";
std::string str(input);

here: http://www.cplusplus.com/reference/string/string/string/

if you want only part so write this:

std::string str(input + from, input + to);

std::string has a constructor that takes an iterator pair. You can substitute pointers for it..

Example:

#include <iostream>


int main() 
{
    char input[]="I love you";

    std::string str = std::string(&input[2], &input[6]);
    std::cout<<str;
    return 0;
}

Here is an example in which the following constructor

basic_string(const charT* s, size_type n, const Allocator& a = Allocator());

is called

#include <iostream>
#include <string>

int main()
{
    char input[] = "I love you";
    std::string s( input + 2, 4 );

    std::cout << s << std::endl;
}

Or you can use constructor

basic_string(const basic_string& str, size_type pos, size_type n = npos,
             const Allocator& a = Allocator());

as in this example

#include <iostream>
#include <string>

int main()
{
    char input[] = "I love you";
    std::string s( input, 2, 4 );

    std::cout << s << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM