-3

I want to encypt a string by adding +1 (ascii) to every char in the string This my attempt

public static string encrypt(string str){
for(int i = 0; i < str.length(); i++){
    int x = str.charAt(i) ;
    x = x + 1; 
}

// Now how can I complete this loop to produce a new string with encrypting the string by adding 1 to every char?

1
  • Note that +1 on an integer type like char produces round robin from 32767 to -32768 or from 65535 to 0. Also, I believe java follows the straightforward 16-bit encoding of its character set (the BMP of the UCS) meaning "+1" may not necessarily yield the code point number of a genuine valid character in the character set. See e.g. the grey boxes at en.wikibooks.org/wiki/Unicode/Character_reference/2000-2FFF . All that kind of stuff may produce "funny" results. Commented Feb 4, 2019 at 14:18

1 Answer 1

0

I suggest you try the following :

Public static string encrypt(string str){
    String result = "";   
    for(int i=0; i<str.length() ; i++){
        int x = str.charAt(i) ;
        x = x+1 ;
        result+= Character.toString((char)x);
    }
    return result;
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Good solution. Although it would be better if you use StringBuilder to avoid copying the whole result string each time you append a character to it
Yes it would be a little bit more faster.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.