-1

I'm trying to write a code changes the characters in a string that I enter. This is the mapping that I have to follow when changing the characters.

String letters = "abcdefghijklmnopqrstuvwxyz";  
String enc = "kngcadsxbvfhjtiumylzqropwe";

By searching through stackoverflow I found out that a string cannot be changed, so I need to create a new string with the converted characters. My problem is that I don't know how to do that. So far I have been able to access each character in the string and print them. I know the solution to this is to access each character, change them then add them to the new string, this is what I don't know how to do or to look up.

public static void main(String[] args) 
{
int cdcode;

//String letters = "abcdefghijklmnopqrstuvwxyz"; 
//String enc =     "kngcadsxbvfhjtiumylzqropwe";
String myString;
char ch;
int strLen;
int chrPos;
   do
   {

    System.out.println("Enter 1 to encode, 2 to decode, 3 to quit:");

    Scanner myCode = new Scanner(System.in);
    Scanner myText = new Scanner(System.in);

    cdcode = myCode.nextInt();


    switch(cdcode)
    {
        case 1: 
            System.out.println("Enter the text to encode: ");
            myString = myText.nextLine();
            strLen = myString.length();
            System.out.println("String Length is: " +myString.length());

            for(chrPos = 0; chrPos < strLen ;chrPos++)
            {
                System.out.println("The Letters are: " +myString.charAt(chrPos));
                if(myString.charAt(chrPos)== 'S')
                {
                System.out.println("It is an S");
                }
            }
            break;


        case 2:
        System.out.println("Enter the text to decode: ");
        myString = myText.nextLine();
        break;

    }

   }while(cdcode != 3);
}
  • An easy way to start is to find the offset of the letter in the first String and then replace the letter with that at the same offset in the second String – Sean Patrick Floyd Oct 05 '18 at 01:55

7 Answers7

2

Use StringBuilder(mutable). Usage:

StringBuilder myString = new StringBuilder(someString);

StringBuilder is the recommended unless the object can be modified by multiple threads. If the object can be modified by multiple threads then use StringBuffer(also mutable).

HaroldSer
  • 2,025
  • 2
  • 12
  • 23
  • Thanks for the response HaroldSer but can you please elaborate more on what I need to do. I understand that with the StringBuilder I can now put the entered characters into the StringBuilder and to manipulate the characters I need to use a for loop but how do I actually compare the character to String enc and change an 'a' character to a 'k' character and so on? – LearningProgramming Oct 05 '18 at 08:40
2

If you want to change paticular character in the string then use replaceAll() function.

String ss = letters.replaceAll("a","x");

If you want to manually check all characters in string, then iterate over each character in the string, do if condition for each character, if change required append the new character else append the same character using StringBuilder.

StringBuilder br = new StringBuilder();
for (int i = 0; i < letters.length(); i++) {
    if (letters.charAt(i) == 'a') 
        br.append("s");
    else
        br.append(letters.charAt(i));
    }
System.out.println(br.toString());
Nithyananth
  • 74
  • 10
0

If I understand your question correctly, you could create a HashMap with key=unencoded letter and value=encoded letter.

Build your new string from an input by checking each letter of that input against the keys in the map. Use the returned values to build your new string.

TedPoch
  • 31
  • 5
0

you can use the + operator (or +=) to add chars to the new string.

here is an example

    String str1 = "abcdef";
    String str2 = "";
    for (int i = 0; i < str1.length(); i++)
        str2 += String.valueOf(str1.charAt(i)).toUpperCase();
    System.out.println(str1 + " ==> " + str2);
Serge
  • 11,616
  • 3
  • 18
  • 28
0

Here you go You can use StringBuilder with setCharAt method without creating too many Strings and once done, convert the StringBuilder to String using toString() method

Below works for me

 String input = new String("stack overflow");
 StringBuilder decoded = new StringBuilder(input);

 for(int idx = 0 ; idx < decoded.length(); idx++){
   if(letters.indexOf(decoded.charAt(idx)) != -1){
     decoded.setCharAt(idx, enc.charAt(letters.indexOf(decoded.charAt(idx))));
   }
 }
 System.out.println(decoded.toString());

\\Input
\\String input = new String("stack overflow");

\\Output
lzkgf iraydhio
Amit Phaltankar
  • 3,341
  • 2
  • 20
  • 37
0

There are a lot of ways of approaching this problem, but this might be simplest to understand for someone learning the language:

public String encode(String str){

    char[] chars = str.toCharArray();

    StringBuilder builder = new StringBuilder();
    for (Character character : chars){
        char encoded = encodeChar(character);
        builder.append(encoded);
    }
    return builder.toString();
}

public String decode(String str){

    char[] chars = str.toCharArray();

    StringBuilder builder = new StringBuilder();
    for (Character character : chars){
        char decoded = decodeChar(character);
        builder.append(decoded);
    }
    return builder.toString();
}

public char encodeChar(char character){
    ...do the voodoo that you do...
}

public char decodeChar(char character){
    ...undo the voodoo...   
}

(StringBuilder is a better choice in this case because synchronization isn't necessary; see Difference between StringBuilder and StringBuffer)

Bill Horvath
  • 1,336
  • 9
  • 24
-1

Use StringBuffer class. Create new StringBuffer() and add the character via append({char}) method. Once all characters are appended, convert StringBuffer to String via toString() method.

Darrell Teague
  • 4,132
  • 1
  • 26
  • 38
Kavya
  • 19
  • 4
  • 1
    As per the Javadocs *The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.* – Scary Wombat Oct 05 '18 at 02:29