Convert a String into a square matrix grid of characters

Given a string of length L. The task is to convert the string into a grid.

  • No. of rows >= floor(√L)
  • No. of columns <= ceil(√L)

Examples:

Input : str = "haveaniceday"
Output :  have
          anic
          eday    

Explanation: sqrt(12) = 3.46, Rows = 4, Columns = 3

Input :str = "geeksforgeeks"
Output : geek
         forg
         geek
         s

Note: Ensure that row*column >= length of the string



Approach:

  1. If (row * column) is less than L then row is equally assigned to column.
  2. Make a 2d character array of (rows * column) size.
  3. Assign the values to the 2d character array from the characters of the given string.
  4. Print the 2d character array.

Below is the implementation of the above approach.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
  
// Function to string into grid form
void gridStr(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];
    // convert the string into grid
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < column; j++) {
            s[i][j] = str[k];
            k++;
        }
    }
  
    // Printing the 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;
    }
}
  
// Driver code
int main()
{
    string str = "GEEKSFORGEEKS";
    gridStr(str);
      
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the
// above approach
class GFG
{
  
    // Function to string into grid form
    static void gridStr(String str)
    {
        int l = str.length();
        int k = 0, row, column;
        row = (int) Math.floor(Math.sqrt(l));
        column = (int) Math.ceil(Math.sqrt(l));
  
        if (row * column < l)
        {
            row = column;
        }
  
        char s[][] = new char[row][column];
          
        // convert the string into grid
        for (int i = 0; i < row; i++) 
        {
            for (int j = 0; j < column; j++) 
            {
                if(k < str.length())
                    s[i][j] = str.charAt(k);
                k++;
            }
        }
  
        // Printing the grid
        for (int i = 0; i < row; i++) 
        {
            for (int j = 0; j < column; j++)
            {
                if (s[i][j] == 0
                {
                    break;
                }
                System.out.print(s[i][j]);
            }
            System.out.println("");
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str = "GEEKSFORGEEKS";
        gridStr(str);
    }
}
  
//This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the
# above approach
  
# From math lib import sqrt,
# floor and ceil function
from math import sqrt, floor, ceil
  
# Function to string into grid form 
def gridStr(string) :
  
    l = len(string)
    k = 0
      
    row = floor(sqrt(l)) 
    column = ceil(sqrt(l)) 
  
    if (row * column < l) :
        row = column
      
    s = [[0 for j in range(column) ] 
            for i in range(row)]
      
    # convert the string into grid 
    for i in range(row) :
        for j in range(column) : 
              
            if k >= l :
                s[i][j] = " "
                k += 1
                  
            else :
                s[i][j] = string[k] 
                k += 1
  
    # Printing the grid 
    for i in range(row) :
        for j in range(column) :
            if s[i][j] == " " :
                break
                  
            print(s[i][j], end = "")
          
        print()
      
# Driver code 
if __name__ == "__main__" :
  
    string = "GEEKSFORGEEKS"
      
    gridStr(string)
  
# This code is contributed by Ryuga 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the
// above approach
using System;
  
class GFG
{
  
    // Function to string into grid form
    static void gridStr(String str)
    {
        int l = str.Length;
        int k = 0, row, column;
        row = (int) Math.Floor(Math.Sqrt(l));
        column = (int) Math.Ceiling(Math.Sqrt(l));
  
        if (row * column < l)
        {
            row = column;
        }
  
        char [,]s = new char[row,column];
          
        // convert the string into grid
        for (int i = 0; i < row; i++) 
        {
            for (int j = 0; j < column; j++) 
            {
                if(k < str.Length)
                    s[i,j] = str[k];
                k++;
            }
        }
  
        // Printing the grid
        for (int i = 0; i < row; i++) 
        {
            for (int j = 0; j < column; j++)
            {
                if (s[i, j] == 0) 
                {
                    break;
                }
                Console.Write(s[i, j]);
            }
            Console.WriteLine("");
        }
    }
  
    // Driver code
    public static void Main()
    {
        String str = "GEEKSFORGEEKS";
        gridStr(str);
    }
}
  
/* This code contributed by PrinciRaj1992 */

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP implementation of the
// above approach
  
// Function to string into grid form
function gridStr($str)
{
    $l = strlen($str);
    $k = 0;
    $row = floor(sqrt($l));
    $column = ceil(sqrt($l));
  
    if ($row * $column < $l)
        $row = $column;
  
    $s = array_fill(0, $row
         array_fill(0, $column, ""));
    // convert the string into grid
    for ($i = 0; $i < $row; $i++) 
    {
        for ($j = 0; $j < $column; $j++)
        {
            if(!empty($str[$k]))
            $s[$i][$j] = $str[$k];
            $k++;
        }
    }
  
    // Printing the grid
    for ($i = 0; $i < $row; $i++)
    {
        for ($j = 0; $j < $column; $j++) 
        {
            if ($s[$i][$j] == '\0')
                break;
            echo $s[$i][$j];
        }
        echo "\n";
    }
}
  
// Driver code
$str = "GEEKSFORGEEKS";
gridStr($str);
  
// This code is contributed by mits
?>

chevron_right


Output:

GEEK
SFOR
GEEK
S


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.