反转字符串中交替的 k 个字符


简介

在本教程中,我们将使用 C++ 编程逻辑实现示例,以反转输入字符串中交替的 k 个字符。我们定义 k 的值来反转给定字符串中的字符。K 是要反转的字符数。K 的值可以是任何值。如果 k 的值大于字符串中字符的总数,我们不会反转任何字符串字符。

演示 1

String = “tutorialspoint” K = 4

输出

otutrialiopsnt

在上面的演示中,我们考虑一个字符串“tutorialspoint”来反转其交替的 4 个字符。k 的值为 4。K=4 表示反转前 4 个字符,然后反转接下来的 4 个字符,依此类推,直到覆盖整个字符串。在反转给定字符串中交替的 k 个字符后,输出为 otutrialiopsnt。

演示 2

String = “hello” K = 2

输出

ehllo

在上面的演示中,我们采用输入字符串“hello”。k 的值为 2。我们反转输入字符串中交替的 2 个字符。反转后,输出为“ehllo”。

C++ 库函数

语法

length(): 它是一个字符串类库函数,返回字符串的长度。字符串的字节格式长度是字符串中所有字符的总和。

string_name.length();

size(): 它是在 <std> 头文件中定义的标准库函数。它返回字符串的大小。

string_name.size();

reverse(): 此库函数在标准模板 C++ 库中定义。它更改字符串字符的顺序。为了反转字符串,它需要两个参数:字符串的起始指针和结束指针。

reverse(string_name.begin(), string_name.end());

算法

  • 获取输入字符串。

  • 定义 k 的值。

  • 反转输入字符串的前 k 个字符。

  • 跳过字符串中的接下来的 k 个字符。

  • 反转字符串中的其他 k 个字符。

  • 打印反转后的字符串。

示例 1

我们通过考虑输入字符串来实现上述问题。首先反转输入字符串的 k 个字符,然后使用公式 k*2 索引值跳到下一个交替的 k 个字符。

Open Compiler
#include <bits/stdc++.h> using namespace std; // user-defined function to reverse the alternate k characters of the string string reverseString(string str, int k, int l){ for (int x = 0; x < str.size();){ // when the string has characters less the the value of k if (x + k > l) break; //reversing the starting characters of k value reverse(str.begin() + x, str.begin() + x + k); // moving in the string for reversing k characters x += 2 * k; } return str; } // Controller int main(){ string str = "tutorialspoint"; int l = str.length(); int k = 4; cout << "The reversed string is: "<< reverseString(str, k, l); return 0; }

输出

The reversed string is: otutrialiopsnt

示例 2

在此实现中,我们遍历输入字符串“tutorialspoint”并将 k 的值定义为 2。创建一个用户定义的函数 reverseString(),该函数通过反转 k 个字符并跳过接下来的 k 个字符来遍历字符串。此过程持续到覆盖整个字符串。

Open Compiler
#include <bits/stdc++.h> using namespace std; // User-defined function to reverse alternate k characters //of the input string string reverseString(string s, int k, int m){ string result = ""; int x = 0, y = 0; // Traversing the string s till the end while (x < m){ // Traversing the string till the last character and trading backward for (y = min(x + k, m) - 1; y >= x; y--) result += s[y]; x = min(x + k, m); // Traversing the string for the x to x+k characters for (y = x; y < min(x + k, m); y++) result += s[y]; x = y; } // Returning result return result; } // Controller int main(){ string s = "tutorialspoint"; int M = s.length(); int K = 2; cout << "The reversed string for every alternate k character is : "<< reverseString(s, K, M); return 0; }

输出

The reversed string for every alternate k character is : uttoiralpsoitn

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

结论

我们已经到达本教程的结尾。在本教程中,我们实现了两个示例来反转输入字符串中交替的 k 个字符。对于每个实现,定义 k 的值。使用 C++ 库的 length() 和 size() 函数查找输入字符串的长度,以便可以遍历它。

使用两个输入字符串演示了任务,并解释了 C++ 实现如何生成结果。

更新于: 2023年8月18日

242 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告