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

แปลงสตริงเป็นตารางมาตริกซ์สี่เหลี่ยมจัตุรัสของตัวอักษรใน C++

คำอธิบายปัญหา

ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมแปลงสตริงเป็นตารางมาตริกซ์สี่เหลี่ยมจัตุรัส (square matrix grid) ของตัวอักษร

สำหรับนี้ เราจะได้รับสตริงของตัวอักษร งานของเราคือพิมพ์สตริงที่กำหนดนั้นในรูปแบบของตารางมาตริกซ์ที่มีจำนวนแถวและคอลัมน์ที่กำหนด

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

#include <bits/stdc++.h> using namespace std; //converting the string in grid format void convert_grid(string str){    int l = str.length();    int k = 0, row, column;    row = floor(sqrt(l));    column = ceil(sqrt(l));    if (row * column < l)       row = column;    char s[row][column];    for (int i = 0; i < row; i++) {       for (int j = 0; j < column; j++) {          s[i][j] = str[k];          k++;       }    }    //printing the new grid    for (int i = 0; i < row; i++) {       for (int j = 0; j < column; j++) {          if (s[i][j] == '\0')             break;          cout << s[i][j];       }       cout << endl;    } } int main(){    string str = "TUTORIALSPOINT";    convert_grid(str);    return 0; }

ผลลัพธ์

TUTO RIAL SPOI NT