String replace method | Encryption & Decryption

string replace java
javascript string replace all
string replace python
string.replace c#
javascript string replace multiple
string replace php
string replace c++
javascript replace all instances

The task is quite simple:

You have just been hired by the CIA as a programmer in the encryption department. Your job is to write a class called Crypto. One method, encrypt, will accept a String that represents the sentence to be encrypted. It will return a String that is the sentence with all v’s (big or small) replaced with "ag’,r", all m’s (big or small) with "ssad", all g’s (big or small) with "jeb..w", and all b’s (big or small) with "dug>?/".

The class contains another method, decrypt, that accepts a String that represents the sentence to be decrypted. In this method the reverse process described above is performed. It returns a String that is the original sentence before encryption.

My encrypt and decrypt methods work completely fine. It's just that it doesn't encrypt/decrypt how it's supposed to. Here's what a sample test run should look like:

Enter a sentence that is to be encrypted: *This is a very big morning.* 
Original sentence = This is a very big morning.
Encrypted sentence = This is a ag',rery dug>?/ijeb..w ssadorninjeb..w. 
Decrypted sentence = This is a very big morning.

And here's what my output looks like:

Enter a sentence that is to be encrypted: This is a very big morning. 
Original sentence = This is a very big morning.
Encrypted sentence = This is a ajedug>?/..w',rery dug>?/ijedug>?/..w ssadorninjedug>?/..w.
Decrypted sentence = This is a very big morning.

As you can tell the encrypted sentence doesn't quite match up, and I know why, I just don't know how to fix it.

Here are my methods:

String encrypt(String string) {
    return string
            .replace("v", "ag',r").replace("V", "ag',r")
            .replace("m", "ssad").replace("M", "ssad")
            .replace("g", "jeb..w").replace("G", "jeb..w")
            .replace("b", "dug>?/").replace("B", "dug>?/");

}

String decrypt(String string) {
    return string
            .replace("dug>?/", "b")
            .replace("jeb..w", "g")
            .replace("ssad", "m")
            .replace("ag',r", "v");
}

Any help/guidance is appreciated!

Your output is wrong because you are replacing v with ag',r, but then replacing the g in ag',r with jeb..w. You should not replace what is already replaced.

To fix this, you need to start with an empty string, and check each character individually. If it is a v, m, g, or b, you append the corresponding gibberish to the string. If it is none of those letters, you append that letter.

Here, I did just that with a StringBuilder:

private static String encrypt(String s) {
    StringBuilder builder = new StringBuilder();
    s.chars().forEach(x -> {
        char c = (char)x;
        if (c == 'v' || c == 'V') {
            builder.append("ag',r");
        } else if (c == 'm' || c == 'M') {
            builder.append("ssad");
        } else if (c == 'g' || c == 'G') {
            builder.append("jeb..w");
        } else if (c == 'b' || c == 'B') {
            builder.append("dug>?/");
        } else {
            builder.append(c);
        }
    });
    return builder.toString();
}

Edit:

The task specifically says to use string methods and not any external classes

In that case you can't use a StringBuilder and has to use a String, but it's the same idea. You just use += to append to it.

You also probably can't use forEach either. You need a normal for loop that loops through the indices of the string.

How to replace a substring in Java?, String replace() : This method returns a new string resulting from replacing all occurrences of old characters in the string with new characters. Syntax: public String replace(char oldch, char newch) Parameters: oldch : the old character. newch : the new character. Because this method returns the modified string, you can chain together successive calls to the Replace method to perform multiple replacements on the original string. Method calls are executed from left to right. The following example provides an illustration. String s = "aaa" ; Console.WriteLine ( "The initial string: ' {0}'", s); s = s

Other method could be (assuming there will be no occurrences of {1}, {2}, {3}, {4} markers in the original text) to do something like this:

static String encrypt(String string) {
    String encryptedWithNumbers = string
          .replace("v", "{1}")
          .replace("V", "{1}")
          .replace("m", "{2}")
          .replace("M", "{2}")
          .replace("g", "{3}")
          .replace("G", "{3}")
          .replace("b", "{4}")
          .replace("B", "{4}");

     return encryptedWithNumbers
          .replace("{1}", "ag',r")
          .replace("{2}","ssad")
          .replace("{3}", "jeb..w")
          .replace("{4}", "dug>?/");
}

Replace Character in a String in Java without using replace() method, Java String replace(CharSequence target, CharSequence replacement) method example. public class ReplaceExample2{ public static void main(String args[]){ String s1="my name is khan my name is java"; String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was" System.out.println(replaceString); The replace () method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. Note: If you are replacing a value (and not a regular expression ), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g

Thank you all for the help! Here's my final (working) code:

String encrypt(String string) {

    String s = "";

    for (int i = 0; i < string.length(); i++) {
        char c = string.charAt(i);
        if (c == 'v' || c == 'V') {
            s += "ag',r";
        } else if (c == 'm' || c == 'M') {
            s += "ssad";
        } else if (c == 'g' || c == 'G') {
            s += "jeb..w";
        } else if (c == 'b' || c == 'B') {
            s += "dug>?/";
        } else {
            s += c;
        }
    }

    return s;

}

String conversions are implemented through the method toString , defined by Returns a new string resulting from replacing all occurrences of oldChar in this  PowerShell Replace can be used to replace character strings, texts or special characters. PowerShell has a Replace “Method” and a Replace “Operator”. This guide covers how to use both. PowerShell Replace “Method” In this section I will discuss how to use PowerShell Replace “Method”. In PowerShell, a “Method” is a set of

Returns a new string in which all occurrences of a specified Unicode character or in the current string are replaced with another specified Unicode character or . String variable before applying the replace method remains the same after applying the replace method. Replace method replaces all the characters in the string with the new character. Syntax: In the following syntax, it is given how a character is being replaced. In the replace method, there are two parameters, the first parameter is the

Python String replace() Method - Python string method replace() returns a copy of the string in which the occurrences of old have been replaced with new,  In the process model, once the MainSequence callback is finished, the variable Locals.ResultList[0].TS.SequenceCall.ResultList contains all the results i need. What i need to do is search for a specific text (

Java String replace() method replaces every occurrence of a given character with a new character and returns a new string. This method allows  In c#, Bitwise Operators will work on bits and these are useful to perform a bit by bit operations such as Bitwise AND (&), Bitwise OR (|), Bitwise Exclusive OR (^), etc. on operands and we can perform bit level operations on Boolean and integer data. For example, we have an integer variables a = 10, b = 20 and the binary format of these

Comments
  • You're making several subsequent replacements. So you first replace tye v by ag',r, and then the g by jeb..w. But you're only supposed to replace the characters of the original string. Not the characters introduced by a previous replacement. You must do a single pass.
  • Your implementation: occurrence of v is replaced by ag',r (applied to the whole phrase), then the g from ag',r is replaced by jeb..w - this was not expected by original task. Basically, you cannot use replace method, you need to iterate over the phrase letter by letter and assemble a new phrase (using for instance StringBuilder).
  • @VladimirL. I realise the issue. I just don't know how to fix it. The task specifically says to use string methods and not any external classes. Any ideas?
  • @Krish See the edit to my answer.