用字符串创建数组

时间:2013-10-25 17:52:22

标签: c++ arrays string

我是C ++的新手,我遇到了一个问题...我似乎无法使用for循环从字符串创建一个字符数组。例如,在JavaScript中你会写这样的东西:

var arr = [];
function setString(s) {
    for(var i = s.length - 1; i >= 0; i--) {
       arr.push(s[i]);
    }
    return arr.join("");
}

setString("Hello World!"); //Returns !dlroW olleH

我知道它有点复杂,我对如何做有一些背景知识但是它的语法对我来说仍然不太熟悉。

有没有办法在c ++中使用数组做到这一点? 我可以像在JavaScript中一样将数组元素加入到一个字符串中吗?

如果你能提供帮助,我们将非常感激。提前致谢。 如果有人需要更多信息,请告诉我,我会编辑帖子。

顺便说一句,我的c ++代码现在非常混乱,但我知道我在做什么......我尝试过的是:

function setString(s) {
    string arr[s.size() - 1];
    for(int i = s.size() - 1; i >= 0; i--) {
        arr[i] = s.at(i); //This is where I get stuck at... 
    //I don't know if I'm doing something wrong or not.
    }
}

如果有人告诉我我做错了什么或者我需要放置或取出代码,那将是件好事。它是在Code :: Blocks

中编译的控制台应用程序

3 个答案:

答案 0 :(得分:3)

std::string使用c_str()方法返回C样式字符串,该字符串只是一个字符数组。

示例:

std::string myString = "Hello, World!";
const char *characters = myString.c_str();

答案 1 :(得分:1)

最直接翻译你的功能:

string setString(string s) {
    string arr;
    for(int i = s.length() - 1; i >= 0; i--) {
        arr.push_back(s[i]);
    }
    return arr;
}

答案 2 :(得分:1)

std::string是一个相当薄的包装器下面的动态数组。没有必要逐个字符地复制,因为它会为您正确地执行:

如果字符数组以空值终止(即最后一个元素为'\0'):

const char* c = "Hello, world!"; // '\0' is implicit for string literals
std::string s = c; // this will copy the entire string - no need for your loop

如果字符数组不是以空值终止的:

char c[4] = {'a', 'b', 'c', 'd'}; // creates a character array that will not work with cstdlib string functions (e.g. strlen)
std::string s(c, 4); // copies 4 characters from c into s - again, no need for your loop

如果您不能使用std::string(例如,如果您被迫使用ANSI C):

const char* c = "Hello, World!";
// assume c2 is already properly allocated to strlen(c) + 1 and initialized to all zeros 
strcpy(c2, c);

在你的javascript示例中,你正在反转字符串,这可以很容易地完成:

std::string s = "Hello, world!";
std::string s1(s.rbegin(), s.rend());

此外,如果您修复了循环(下面的伪代码),您可以将迭代次数减少一半(对于C ++和Javascript):

string s = "Hello, world!"
for i = 0 to s.Length / 2
    char t = s[i]
    s[i] = s[s.Length - 1 - t]
    s[s.Length - 1 - i] = t

将交换字符串的末尾以反转它。不是循环遍历N个项目,而是循环最多N / 2个项目。

相关问题