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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top