Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help needed regarding appending character

 
Divya Sanjeev
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package learn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class AddCharDemo {

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the string:: ");
String s = br.readLine();
int l = s.length();
StringBuffer sb = new StringBuffer(s);
for(int i = (l-1);i>=0;i--){
if(sb.charAt(i)=='a'){
sb.append('e');
}
}
System.out.println("String after addition is:: " + sb.toString());

}

}

Hi All,

I just wanted to add a char 'e' next to 'a' wherever it is found. But this program of mine will append at the end of the string. Please help.

Thanks,
Divya
 
Thakur Sachin Singh
Ranch Hand
Posts: 248
Hibernate Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use method setCharAt(int index,char ch)
 
Divya Sanjeev
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Thakur,

If I use setCharAt(), it is setting the desired char at that index position. But I would like to add it after the char which I have given in the if condition.


if(sb.charAt(i)=='a'){
sb.setCharAt(i, 'e');
}
 
Thakur Sachin Singh
Ranch Hand
Posts: 248
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can use
 
Swastik Dey
Rancher
Posts: 1603
5
Android Java Java ME
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just a note, if its not a multithreaded operation, use StringBuilder instead of StringBuffer. Because StringBuffer is thread safe and will make the operation slow.
 
Thakur Sachin Singh
Ranch Hand
Posts: 248
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
your code was so confusing, you can use below code it is very simple.


 
Divya Sanjeev
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much ...Its working fine now
 
Thakur Sachin Singh
Ranch Hand
Posts: 248
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You want every occurrence of 'a' to be replaced by 'ae'. Why not simply use String.replace? What am I missing?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic