Almac
Almac

Reputation: 227

How to replace string characters from an array

I'm trying to create an encryption scheme that replaces the letters in a String with a corresponding letter.

For example, in the string "apple", the "a" is replaced with "k", and so on. Each letter has a fixed corresponding letter.

I want to get user input and store it into an array. Then I want to loop through the array and find each index of the String. Then replace each index with the corresponding letter.

Here's what I cooked up so far but I'm unable to make the code run. I'm mainly getting, error: incompatible types.

I can't determine whether I should be using the charAt method and changing my variable types to char.

import java.util.*;

public class Encrypt {

    public static void main(String [] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the String Name to encrypt:");
        String inputString = input.nextLine();
        String[] str = new String[inputString];
        replaceString();
    }

    public static void replaceString() {

        for(int i = 0; i < str.length(); i++) {
            if(str.indexOf(i) == "a") {
                str.indexOf(i) = "k";
            } else if(str.indexOf(i) == "b") {
                str.indexOf(i) = "n";
            }
            //and so on A-Z...
            System.out.print(str);
        }

    }
}

Upvotes: 2

Views: 12759

Answers (3)

akhil_mittal
akhil_mittal

Reputation: 24167

Why do you want to use String[]? IMO you should use char[] and the following code will do what you want:

public static void main(String[] args) throws IOException {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the String Name to encrypt:");
    String inputString = input.nextLine();
    char[] str = inputString.toCharArray();
    replaceString(str);
}

public static void replaceString(char[] str) {
    int length = str.length;
    for(int i = 0; i < length; i++) {
        if(str[i] == 'a') {
            str[i] = 'k';
        } else if(str[i] == 'b') {
            str[i] = 'n';
        }
    }
        System.out.println(Arrays.toString(str));
        System.out.println(String.valueOf(str));
}

Running the program:

Enter the String Name to encrypt: bat
[n, k, t] nkt

Upvotes: 2

user2575725
user2575725

Reputation:

Problem is String.indexOf() gives you index of first occurence. It won't replace the string.

str.indexOf(i) = "k"; //won't replace anything here

BTW, there are several other syntax errors in your code.

Try this example, if you want use loops:

import java.util.Scanner;
class Ideone {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the String Name to encrypt:");
    String str = input.nextLine();
    input.close();
    str = replaceString(str); // note, self assignment
    System.out.println(str);
  }

  public static String replaceString(String str) {
    char[] tmp = str.toCharArray();// get all into array
    for (int i = 0; tmp.length > i; i++) {
      if ('a' == tmp[i]) {
        tmp[i] = 'k';
      } else if ('b' == tmp[i]) {
        tmp[i] = 'n';
      }
    }
    return new String(tmp); //create new string with modified array
  }
}

Run code here

As suggested by others, you may also look into String.replaceAll():

import java.util.Scanner;
class Ideone {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the String Name to encrypt:");
    String str = input.nextLine();
    input.close();
    str = replaceString(str);
    System.out.println(str);
  }

  public static String replaceString(String str) {
    return str.replaceAll("a", "k").replaceAll("b", "n");
  }
}

Run code here

Upvotes: 1

Michael
Michael

Reputation: 2773

You're looking for String#replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

Your code would have to loop a pre-determined amount of times and store each String in the array

Scanner input = new Scanner(System.in);
String[] str = new String[5];
for (int i = 0; i < 5; i++){
    System.out.println("Enter the String Name to encrypt:");
    String inputString = input.nextLine();
    str[i] = inputString.replace('a', 'k');
}
for (String s : str){
    System.out.println("Encrypted word: " + s);
}

NOTE

Your previous way of declaring an array,

String[] str = new String[inputString];

is incorrect. Look here to practice more with arrays. Essentially, the formula is:

Type[] myArr = new Type[sizeOfArray];

Upvotes: 1

Related Questions