操作字符串的函数 ( "abcdef" -> "faebdc" )

Function to manipulate a string ("abcdef" -> "faebdc")

本文关键字:gt faebdc abcdef 字符串 函数 操作      更新时间:2023-10-16

大家好,我正在开发一个函数,以以下方式操作任何字符串。

"abc"->"cab"

"abcd"->"dacb"

"abcdef"->"faebdc"

"diversinta"->"adtinveeg"

等等

这是我迄今为止想出的代码。我认为它能起到作用,但我认为代码和解决方案有点难看,我不确定它是否能防故障,是否能在每个给定的情况下正常工作。我将非常感谢对这段代码的任何输入,或关于如何编写此函数的任何示例。我恳求你记住,我是一个非常优秀的人,所以不要对我太苛刻

string transformer(string input) {
string temp;
int n = 0;
int m = (input.length() -1);
for( int i = 0; i < input.length(); i++) {
    temp += input[m];
    if (input[m] == input[n]) {
        break;
    }
    else {
        temp += input[n];
    }
    n += 1;
    m -= 1;
    if ( temp.length() == input.length() ) {
        break;
    }
}
return temp; }

您有三个问题。

试试"abbba"。如果结果不是你想要的,那么这个条件是:

if (input[m] == input[n]) {
break;
}

这完全是错误的。

看看另一个条件:

if ( temp.length() == input.length() ) {
  break;
}

您一次向temp添加两个字符。如果input的长度为奇数怎么办?

假设这是正确的。考虑循环:

for( int i = 0; i < input.length(); i++) {
...
  if ( temp.length() == input.length() ) {
    break;
  }
}

该循环在for语句中永远不会终止。你也可以这样做:

while( temp.length() < input.length() ) {
...
}

一旦这些都正常工作,就应该研究迭代器。

此函数只将两个索引移向中心,直到它们相遇或经过。最后一个if块处理奇数长度输入字符串的情况。它适用于ideone.com 上的所有测试用例

std::string transformer(const std::string& input)
{
    std::string temp;
    int i = 0;
    int j = input.length() - 1;
    while (i < j) {
        temp += input[j--];
        temp += input[i++];
    }
    if (i == j) {
        temp += input[i];
    }
    return temp;
}
std::string transformer(const std::string& input) {
    std::string res(input.length(), '0');
    for (int i = 0; i < input.length(); ++i) {
        res[i] = input[ i % 2 == 0 ? input.length() - (i/2) - 1 : (i/2) ];
    }
    return res;
}

不幸的是,if (input[m] == input[n])将确保如果第一个和最后一个字符相同,则在处理完第一个字符后立即退出。

我会用std::string::iteratorstd::string::reverse_iterator:

auto it = input.begin();
auto rit = input.rbegin();
std::string temp;
for (size_t i = 0; i < input.length()/2; ++i) {
    temp += *rit++;
    temp += *it++;
}

处理空和奇数长度输入的逻辑由您自己来做,不应该太难。(长度为1的输入也是一种特殊情况)

我会使用指针而不是索引来实现这一点。

因此,你有一个指针来读取边,并在每次迭代时不断交换它们。

它也会使它更快。

我认为这应该有效,但我不记得如何制作一个const-char指针数组。有人能帮我走那一步吗?

string transformer(string input) {
     std::string temp;
     const char *front, *back;
     for (*front = input.c_str(), *back = front + input.length() - 1; front < back ; front++, back--) {
        temp += *back;
        temp += *front;
     }
     if (front == back)
        temp += *front;

     return temp;
}

(使用与@Blastfurt相同的方法,但跳过不必要的索引。)