从字符串中获取单个字符串char

时间:2011-12-28 14:42:16

标签: c++

for each (std::string s in m_intro.text) // std::vector<string>
    {
        for (int i = 0; i < s.length(); i++)
        {
            char* chr = &s.at(i);
            chr[i+1] = NULL;
            std::string t(chr);

            // other code is used below not shown as not relivent

        }

    }

我想从字符串中获取char。我得到的每个字符然后我想变成一个字符串(有一个需要const std::string&的函数)

上面的代码只运行一次,但在第一个循环之后,整个s为空。我明白为什么会这样。

我想要的是在每个循环中从s获取下一个字符并将其存储为字符串。

4 个答案:

答案 0 :(得分:10)

char* chr = &s.at(i);
chr[i+1] = NULL;
std::string t(chr);

char是C字符串(或char数组)的一部分时,您使用正确的(如果过时)方法将下一个元素设置为NULL以终止字符串。

然而在这种情况下,这是不相关的;你只是索引到std::string并用NULL替换所有字符,这当然不是你的意思。

std::string有一个构造函数可以用来避免这种肮脏:

std::string t(1, s.at(i));
//   ^        ^    ^
//   |        |    |
// string     |    |
//            |    |
//     of length 1 |
//        char     |
//                 |
//     each having value s.at(i)

无需弄乱指针或char数组或NULL - 终止。

答案 1 :(得分:1)

您可以通过在循环中为其元素分配'\0'来自行清除字符串。你不应该使用字符串的内部。相反,创建一个临时的单字符字符串,并在循环中重新分配其第一个字符,如下所示:

for each (std::string s in m_intro.text) // std::vector<string>
    {
        string tmp("_");
        for (int i = 0; i < s.length(); i++)
        {
            tmp[0] = s[i];

            // other code is used below not shown as not relivent

        }

    }

答案 2 :(得分:1)

这是作业吗?为什么你认为“在第一个循环之后整个s为空”?看起来代码看起来很清楚,它表示缺乏对C / C ++中字符串如何工作的理解......

话虽如此,这是实现您所寻找目标的可能方式:

for each (std::string s in m_intro.text) // std::vector<string>
    {
        for (int i = 0; i < s.length(); i++)
        {
            std::string t = s.substring(i, 1);

            // other code is used below not shown as not relevant
        }

    }

答案 3 :(得分:0)

char* chr = &s.at(i);

这是一个错误。您编辑源字符串,使其元素为第二个\ 0(零终止),截断它。 试试这段代码:

        for (int i = 0; i < s.length(); i++)
        {
            char chrstr[2];
            chrstr[0] = s.at(i);
            chrstr[1] = NULL;
            std::string t(chrstr);

            // other code is used below not shown as not relivent
        }