এই প্রোগ্রাম এর প্রশ্ন "Cracking the Coding Interview" বই থেকে নেয়া। প্রশ্ন টা হচ্ছে - "Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in java, please use a character array so that you can perform this operation in place.)"

input: "Mr John Smith ", 13 output: "Mr%20John%20Smith"

জাভা তে এর সমাধান হচ্ছে - (বই এর ওয়েবসাইট থেকে নেয়া)

public class Question {
    // Assume string has sufficient free space at the end
    public static void replaceSpaces(char[] str, int trueLength) {
        int spaceCount = 0, index, i = 0;
        for (i = 0; i < trueLength; i++) {
            if (str[i] == ' ') {
                spaceCount++;
            }
        }
        index = trueLength + spaceCount * 2;
        if (trueLength < str.length) str[trueLength] = '\0';
        for (i = trueLength - 1; i >= 0; i--) {
            if (str[i] == ' ') {
                str[index - 1] = '0';
                str[index - 2] = '2';
                str[index - 3] = '%';
                index = index - 3;
            } else {
                str[index - 1] = str[i];
                index--;
            }
        }
    }

    public static int findLastCharacter(char[] str) {
        for (int i = str.length - 1; i >= 0; i--) {
            if (str[i] != ' ') {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        String str = "Mr John Smith    ";
        char[] arr = str.toCharArray();
        int trueLength = findLastCharacter(arr) + 1;
        replaceSpaces(arr, trueLength); 
        System.out.println("\"" + AssortedMethods.charArrayToString(arr) + "\"");
    }
}

কেউ বিস্তারিত কোড ব্যাখ্যা করলে খুবই উপকৃত হব।

asked 19 May, 20:06

shuddha7435's gravatar image

shuddha7435
34112

edited 19 May, 20:07

Be the first one to answer this question!
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Question tags:

×215
×69
×38

question asked: 19 May, 20:06

question was seen: 119 times

last updated: 19 May, 20:07