反轉字串中交替的 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 個字元。
#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 個字元來遍歷字串。此過程持續到覆蓋整個字串。
#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
結論
我們已經到達本教程的結尾。在本教程中,我們實現了兩個示例來反轉輸入字串中交替的 k 個字元。對於每個實現,定義 k 的值。使用 C++ 庫的 length() 和 size() 函式查詢輸入字串的長度,以便可以遍歷它。
使用兩個輸入字串演示了任務,並解釋了 C++ 實現如何生成結果。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP