0

Trying to do a simple encryption using Strings, loops and chars. Need to know how to replace the capitalized letters in the String by looping through the sentence and replace characters with a key.

String capitalize = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lower = "abcdefghijklmnopqrstuvwxyz";
String num = "1234567890";
String user = "Hello World 123 (456).";

String encrypt = "";
for (int x = 0; x < user.length(); x++)
{
    char c = user(x);
    if (Character.isUpperCase(c))
    {
        Replace the upper case letters here.
    }

//more code beneath the if but just need help on the first part to get things going

Mark Ball
  • 19
  • 2
  • 2
    You probably want to look at that other question I just answered: http://stackoverflow.com/questions/43310535/adding-to-ascii-code-during-for-loop ... beyond that: keep in mind that such transformations are only valid in terms of "learning how to such things". I hope you understand that nothing that is build on such simple schemes can be called **encryption**. – GhostCat Apr 09 '17 at 19:33
  • ["Schneier's Law"](https://www.schneier.com/blog/archives/2011/04/schneiers_law.html): Anyone, from the most clueless amateur to the best cryptographer, can create an algorithm that he himself can't break. – zaph Apr 09 '17 at 20:49

1 Answers1

1

Strings are immutable in Java, so you'll need to either convert the String user to a character array user.toCharArray() and then perform operations on the characters with array syntax and convert back to String, or create a new String and append characters to it as you loop through the first. For the latter, you can use StringBuilder or the concat operator + (which also just uses StringBuilder).

StringBuilder builder = new StringBuilder();

for (char c : user.toCharArray()) {
   if (Character.isUpperCase(c)){
     builder.append(NEW_CHAR); //NEW_CHAR = char you want to replace c with
   }
   else {
     builder.append(c)
   }
}
return builder.toString();

or

char[] userArr = user.toCharArray();
for (int i = 0; i < userArr.length; ++i) {
 if(Character.isUpperCase(user[i]) {
    user[i] = NEW_CHAR; //NEW_CHAR = char you want to replace user[i] with
 }
}
return String.valueOf(userArr);
Bart W
  • 137
  • 7