Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

วิธี reverse string in place ใน C หรือ C++


ในส่วนนี้เราจะดูวิธี reverse string in place ไม่ใช้ memory อื่น ใน C++ ใช้ std::string แต่ใน C ต้องใช้ character array โปรแกรมนี้ใช้ character array รับ string แล้ว reverse

Input: A string “This is a string” Output: The reversed string “gnirts a si sihT”

Algorithm

reverse_string(str)

Input − The string

Output − The reversed string.

len := the length of the string i := 0 and j := (len-1) while i < j, do swap the characters from position i and j i := i + 1 j := j - 1 done

ตัวอย่างโค้ด

#include <iostream> #include<cstring> using namespace std; void reverse(char s[]) {    int len = strlen(s) ; //get the length of the string    int i, j;    for (i = 0, j = len - 1; i < j; i++, j--) {       swap(s[i], s[j]);    } } int main() { char s[20] = "This is a string"; cout << "Main String: " << s <<endl; reverse(s); cout << "Reversed String: " << s <<endl; }

ผลลัพธ์

Main String: This is a string Reversed String: gnirts a si sihT