0
    String str="b5l*a+i";//trying to replace the characters by user input (integer)
    StringBuffer sb=new StringBuffer(str);
    for(int i=0;i<sb.length();i++)
    {
        for(int j='a';j<='z';j++)
        {
            if(sb.charAt(i)==j)
            {
                System.out.println("Enter value for "+j);
                int ip=sc.nextInt();
                char temp=(char)ip;
                //here how to replace the characters by int????

            }
        }
    }

/* finally it will look like enter value b 4 enter value a 5 enter value i 6 the output is 451*5+6 */

Houssam Badri
  • 2,441
  • 3
  • 29
  • 60
Balaji
  • 1,773
  • 1
  • 17
  • 30
  • what problem are you facing? – Tanuj Yadav Jul 09 '17 at 07:38
  • Related: https://stackoverflow.com/questions/6952363/replace-a-character-at-a-specific-index-in-a-string? – Vikram Jul 09 '17 at 07:46
  • Check out docs for StringBuffer [here](https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html); specifically, the methods [deleteCharAt](https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#deleteCharAt-int-) and [insert](https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#insert-int-int-) might be helpful. – Kevin Anderson Jul 09 '17 at 07:49

3 Answers3

1

With a Regular Expression

You should use regular expressions, it's more elegant and much more powerful. For example, without changing a line of code, you can use variable names that make more than one letter.

Example

Scanner sc = new Scanner(System.in);
String str = "b5l*a+i";

// This pattern could be declared as a constant
// It matches any sequence of alpha characters
Pattern pattern = Pattern.compile("[a-zA-Z]+");

Matcher matcher = pattern.matcher(str);

StringBuffer result = new StringBuffer();

// For each match ...
while(matcher.find()) {
    // matcher.group() returns the macth found
    System.out.println("Enter value for "+ matcher.group());

    Integer input = sc.nextInt();

    // ... append the parsed string with replacement of the match ...
    matcher.appendReplacement(result, input.toString());
}

// ... and don't forget to append tail to add characters that follow the last match 
matcher.appendTail(result);

System.out.println(result);
Sébastien Helbert
  • 2,185
  • 13
  • 22
  • You'll want to `appendTail()` after the loop. Won't matter in this example case, but it will matter if the `String` ends with a number, because otherwise you will lose anything after the last letter. Love the solution, though! – Tim M. Jul 25 '17 at 15:49
  • 1
    Indeed you are absolutely right, `appendTail(...)` is missing. I'll edit my post. This should have been unit tested to do well. – Sébastien Helbert Jul 28 '17 at 12:42
0

Taking your code and adapting it by following up on Kevin Anderson's comment, this seems to do what you're looking for:

Scanner sc = new Scanner(System.in);
String str="b5l*a+i";
StringBuffer sb=new StringBuffer(str);
for(int i=0;i<sb.length();i++)
{
    for(int j='a';j<='z';j++)
    {
        if(sb.charAt(i)==j)
        {
            System.out.println("Enter value for "+(char)j);
            int ip=sc.nextInt();
            sb.deleteCharAt(i);
            sb.insert(i, ip);
        }
    }
}

Might I also suggest this code which would behave similarly?

Scanner sc = new Scanner(System.in);
String str="b5l*a+i";
StringBuffer sb=new StringBuffer(str);
for(int i=0;i<sb.length();i++)
{
    char original = sb.charAt(i);
    if(original >= 'a' && original <= 'z')
    {
        System.out.println("Enter value for "+original);
        int ip=sc.nextInt();
        sb.deleteCharAt(i);
        sb.insert(i, ip);
    }
}

It should be more efficient, as it will not have to loop through the characters.

EDIT

After seeing @Sebastien's excellent answer, and applying some more of my own changes, I believe the following is an even better solution than the above ones, if it fits your project's constraints.

Scanner sc = new Scanner(System.in);
String str = "b5l*a+i";
Matcher matcher = Pattern.compile("[a-z]").matcher(str);
StringBuilder sb = new StringBuilder(str);
while (matcher.find())
{
    System.out.println("Enter value for " + matcher.group());
    int ip = sc.nextInt();
    sb.setCharAt(matcher.start(), Character.forDigit(ip, 10));
}

Here is what is better:

  • Pattern matching with regular expressions. This way you don't need to manually search through each character of the String and check if it is a letter, then decide what to do with it. You can let the Matcher do that for you. The regular expression [a-z] means "exactly one character in the range of a to z. The matcher.find() method returns true each time it finds a new match for that expression as it moves through the String, and false when there are no more. Then, matcher.group() gets the character from the past find() operation (as a String, but that doesn't matter to us). matcher.start() gets the index for the match (the methods are named start() and end() because a typical match will be more than one character and have a start and end index, but only start() matters to us).
  • Switched to StringBuilder. StringBuilder is considered the newer implementation of what StringBuffer was designed for. It is generally preferred to use StringBuilder, unless you need your application to be thread-safe (which you don't, unless you know for sure that you specifically do need it to be). In our case, it also makes the action a lot easier by providing the setCharAt method, which does exactly what we need to do. Now we can just plop in the index of the char we intend to change (which the Matcher so conveniently provides us with), and the new character we got from the input. We must first make a character out of the int, using the convenient static method of the Character class, forDigit. The first part is the digit we read from input, and the second bit is the radix, which it needs to know to determine the digit's validity (for example, in base-10, the input 10 will be invalid, but in base-16, hexadecimal, it will return 'a'), in our case we put 10, because base-10 is the most common English number system. If the input is invalid (i.e. more than one base-10 digit, like 10, or less than 0), it will return a null character, so you may want to pop that out of the forDigit argument and first check if it is null, and handle input accordingly, something like the following:

    char ipChar = Character.forDigit(ip, 10);
    if (ipChar == '\u0000') throw new MyCustomNotADigitException("error message");
    sb.setCharAt(matcher.start(), ipChar);
    
Tim M.
  • 598
  • 5
  • 15
  • No problem, glad I could help. If you don't want to wait for an answer next time, the specific list of methods that each class in the Java Class Library has, and what each method does, can be found [here.](https://docs.oracle.com/javase/8/docs/api/) It can be extremely useful. – Tim M. Jul 18 '17 at 12:43
0
String str = "muthu", str1 = "";
        int n = 5;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == 'u') {
                str1 = str1 + n;
            } else
                str1 = str1 + str.charAt(i);
        }