关于c ++:将字符串转换为char *

convert string to char*

本问题已经有最佳答案,请猛点这里访问。

布尔奇1(P)Probly A&;or some similar missing(I am noob at CPP).(p)(P)我有(p)字母名称(P)我怎么会有一个共同点(p)


有很多方法。至少有五个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
 * An example of converting std::string to (const)char* using five
 * different methods. Error checking is emitted for simplicity.
 *
 * Compile and run example (using gcc on Unix-like systems):
 *
 *  $ g++ -Wall -pedantic -o test ./test.cpp
 *  $ ./test
 *  Original string (0x7fe3294039f8): hello
 *  s1 (0x7fe3294039f8): hello
 *  s2 (0x7fff5dce3a10): hello
 *  s3 (0x7fe3294000e0): hello
 *  s4 (0x7fe329403a00): hello
 *  s5 (0x7fe329403a10): hello
 */


#include
#include <string>
#include <cstring>

int main()
{
    std::string s0;
    const char *s1;
    char *s2;
    char *s3;
    char *s4;
    char *s5;

    // This is the initial C++ string.
    s0 ="hello";

    // Method #1: Just use"c_str()" method to obtain a pointer to a
    // null-terminated C string stored in std::string object.
    // Be careful though because when `s0` goes out of scope, s1 points
    // to a non-valid memory.
    s1 = s0.c_str();

    // Method #2: Allocate memory on stack and copy the contents of the
    // original string. Keep in mind that once a current function returns,
    // the memory is invalidated.
    s2 = (char *)alloca(s0.size() + 1);
    memcpy(s2, s0.c_str(), s0.size() + 1);

    // Method #3: Allocate memory dynamically and copy the content of the
    // original string. The memory will be valid until you explicitly
    // release it using"free". Forgetting to release it results in memory
    // leak.
    s3 = (char *)malloc(s0.size() + 1);
    memcpy(s3, s0.c_str(), s0.size() + 1);

    // Method #4: Same as method #3, but using C++ new/delete operators.
    s4 = new char[s0.size() + 1];
    memcpy(s4, s0.c_str(), s0.size() + 1);

    // Method #5: Same as 3 but a bit less efficient..
    s5 = strdup(s0.c_str());

    // Print those strings.
    printf("Original string (%p): %s
"
, s0.c_str(), s0.c_str());
    printf("s1 (%p): %s
"
, s1, s1);
    printf("s2 (%p): %s
"
, s2, s2);
    printf("s3 (%p): %s
"
, s3, s3);
    printf("s4 (%p): %s
"
, s4, s4);
    printf("s5 (%p): %s
"
, s5, s5);

    // Release memory...
    free(s3);
    delete [] s4;
    free(s5);
}


首先,您必须分配内存:

1
char * S = new char[R.length() + 1];

然后您可以将strcpySR.c_str()一起使用:

1
std::strcpy(S,R.c_str());

如果字符串没有更改或C字符串只使用一次,也可以使用R.c_str()。但是,如果要修改S,则应复制字符串,因为写入R.c_str()会导致未定义的行为。

注:您也可以使用str::copy,而不是strcpy