在第n次出现时反转一个字符串

时间:2013-12-14 19:25:50

标签: c++ c string logic

我有一个字符串str[]="ABCDEFGHI",并说n = 3。我需要为任何输入字符串实现reversestring(arr,n)逻辑,对于任何n值。在这种情况下,我的输出必须是str = "CBAFEDIHG"

如果我的str[]="PQRSTUVWXYZ",对于n = 4,我的输出必须是str = "SRQPWVUTXYZ"。在这种情况下,您可以忽略倒转最后一次出现,因为少于4个字母。

对于input[]="this is a simple test", output[]="sith si a elpmis tset",如果不使用c ++中的函数重载使用任何第n个出现条件,可以推广类似的逻辑。

2 个答案:

答案 0 :(得分:1)

假设您正在处理C风格的字符串,如果您想要反转每n个字符,您可以简单地执行以下操作:

//Iterators
int x, y;
char str[] = "ABCDEFGHI";
int n = 3;
int strLen = strlen(str);

//Assuming C99+ for variable length arrays...
char newStr[strLen + 1];


if (strLen % n != 0) {
    printf("For this simple example the length of str must be a multiple of n\n");
    return 0;
}

for (x = 0; x < strLen; x += n) {
    for (y = 0; y < n; y++) {
        newStr[x + y] = str[x + (n - y) - 1];
    }
}

//Ensure string is terminated properly
newStr[strLen] = 0;

printf("Converted %s to %s\n", str, newStr);

return 0;

就推广这个而言,你给出的第二个例子涉及翻转单词,而不是n个字符的块,因此你需要一个不同的接近,将字符串拆分为单独的单词并反转那些块,这是一个不同的问题

答案 1 :(得分:1)

以下是仅使用一个库函数std::reverse

的示例
#include <iostream>
#include <algorithm>

int main() {
    std::string s1 = "ABCDEFGHI";
    std::string s1_output = "CBAFEDIHG";
    std::string s2 = "PQRSTUVWXYZ";
    std::string s2_output = "SRQPWVUTXYZ";
    int N1 = 3;
    int N2 = 4;

    for (unsigned int i = 0; i < s1.size() / N1; i++)
        std::reverse(s1.begin() + (i * N1), s1.begin() + (i * N1 + N1));
    std::cout << std::boolalpha << (s1 == s1_output) << std::endl; // true
    for (unsigned int i = 0; i < s2.size() / N2; i++)
        std::reverse(s2.begin() + (i * N2), s2.begin() + (i * N2 + N2));
    std::cout << std::boolalpha << (s2 == s2_output) << std::endl; // true
}

您的第二个示例与您的第一个示例不同,因为您在单个单词上操作,而不是范围。它也有所不同,因为您不会忽略小于N的块。

根据评论中的建议,您可以使用std::istringstream并使用提取运算符,在空格之间提取“块”。

#include <iostream>
#include <algorithm>
#include <sstream>
#include <iterator>

int main() {
    std::string s1 = "this is a simple test";
    std::string s1_output = "siht si a elpmis tset"; // you made a typo

    std::istringstream iss(s1);

    std::string chunk;
    std::string output = "";
    while (iss >> chunk) {
        std::reverse(chunk.begin(), chunk.end());
        output += chunk + " ";
    }
    output.erase(output.size() - 1, output.size()); // chop off remaining space
    std::cout << std::boolalpha << (output == s1_output); // true
}
相关问题