Saturday, December 28, 2024
Google search engine
HomeData Modelling & AISplit given String into substrings of size K by filling elements

Split given String into substrings of size K by filling elements

Given a string str of length N and an integer K, the task is to split the string into K sized groups and if the last group does not have K characters remaining, then a character ch is used to complete the group.

Examples:

Input: str = “Algorithms”, K = 3, ch = “@”
Output: Alg ori thm s@@
Explanation:
The first 3 characters “alg” form the first group.
The next 3 characters “ori” form the second group.
The last 3 characters “thm” form the third group.
For the last group, there is only the character ‘s’ from the string. 
To complete this group, add ‘@’ twice.

Input: str = “Algorithm”, K = 3, ch = “@”
Output: Alg ori thm
Explanation:
Similar to the previous example, 
The first 3 characters “alg” form the first group.
The next 3 characters “ori” form the second group.
The last 3 characters “thm” form the third group.
Since all groups can be completely filled by characters from the string, no need to use ch.

 

Approach: This is a simple implementation related problem. Follow the steps mentioned below:

  1. Initialise res as an empty string.
  2. Start traversing the string and when the size of the res string equals K, then place a res string into the result vector and empty the res string again for further division
  3. And at last, if the res string is not empty and size is not equal to k a, use the Extra character to fill it, the last group.

Below is the implementation of the above approach.

C++




// C++ code to implement above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to split the string
vector<string> dividestring(string str,
                            int K, char ch)
{
    int N = str.size();
    int j = 0, i = 0;
    vector<string> result;
    string res = "";
    while (j < N) {
        res += str[j];
        if (res.size() == K) {
            result.push_back(res);
            res = "";
        }
        j++;
    }
 
    if (res != "") {
        while (res.size() < K) {
            res += ch;
        }
        result.push_back(res);
    }
    return result;
}
 
// Driver code
int main()
{
 
    string str = "Algorithms";
    int K = 3;
    char ch = '@';
    vector<string> ans
        = dividestring(str, K, ch);
    for (auto i : ans) {
        cout << i << "\n";
    }
    return 0;
}


Java




// Java code to implement above approach
import java.util.ArrayList;
 
class GFG
{
 
  // Function to split the String
  static ArrayList<String> divideString(String str, int K, char ch) {
    int N = str.length();
    int j = 0;
    ArrayList<String> result = new ArrayList<String>();
    String res = "";
    while (j < N) {
      res += str.charAt(j);
      if (res.length() == K) {
        result.add(res);
        res = "";
      }
      j++;
    }
 
    if (res != "") {
      while (res.length() < K) {
        res += ch;
      }
      result.add(res);
    }
    return result;
  }
 
  // Driver code
  public static void main(String args[])
  {
 
    String str = "Algorithms";
    int K = 3;
    char ch = '@';
    ArrayList<String> ans = divideString(str, K, ch);
    for (String i : ans) {
      System.out.println(i);
    }
  }
}
 
// This code is contributed by gfgking.


Python3




# python3 code to implement above approach
 
# Function to split the string
 
 
def dividestring(str, K, ch):
 
    N = len(str)
    j, i = 0, 0
    result = []
    res = ""
    while (j < N):
        res += str[j]
        if (len(res) == K):
            result.append(res)
            res = ""
 
        j += 1
 
    if (res != ""):
        while (len(res) < K):
            res += ch
 
        result.append(res)
 
    return result
 
 
# Driver code
if __name__ == "__main__":
 
    str = "Algorithms"
    K = 3
    ch = '@'
    ans = dividestring(str, K, ch)
    for i in ans:
        print(i)
 
    # This code is contributed by rakeshsahni


C#




// C# code to implement above approach
using System;
using System.Collections.Generic;
class GFG {
 
  // Function to split the string
  static List<string> dividestring(string str, int K,
                                   char ch)
  {
    int N = str.Length;
    int j = 0;
    List<string> result = new List<string>();
    string res = "";
    while (j < N) {
      res += str[j];
      if (res.Length == K) {
        result.Add(res);
        res = "";
      }
      j++;
    }
 
    if (res != "") {
      while (res.Length < K) {
        res += ch;
      }
      result.Add(res);
    }
    return result;
  }
 
  // Driver code
  public static void Main()
  {
 
    string str = "Algorithms";
    int K = 3;
    char ch = '@';
    List<string> ans = new List<string>();
    ans = dividestring(str, K, ch);
    foreach(var i in ans) { Console.WriteLine(i); }
  }
}
 
// This code is contributed by Taranpreet


Javascript




<script>
    // JavaScript code for the above approach
     
    // Function to split the string
    function dividestring(str, K, ch)
    {
        let N = str.length;
        let j = 0, i = 0;
        let result = [];
        let res = "";
        while (j < N)
        {
            res += str[j];
            if (res.length == K)
            {
                result.push(res);
                res = "";
            }
            j++;
        }
 
        if (res != "") {
            while (res.length < K) {
                res += ch;
            }
            result.push(res);
        }
        return result;
    }
 
    // Driver code
    let str = "Algorithms";
    let K = 3;
    let ch = '@';
    let ans
        = dividestring(str, K, ch);
    for (let i of ans) {
        document.write(i + '<br>')
    }
 
     // This code is contributed by Potta Lokesh
</script>


 
 

Output: 

Alg
ori
thm
s@@

 

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments