The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes help needed regarding appending character Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "help needed regarding appending character" Watch "help needed regarding appending character" New topic
Author

help needed regarding appending character

Divya Sanjeev
Greenhorn

Joined: Dec 16, 2009
Posts: 18
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

Joined: Jun 15, 2010
Posts: 205

use method setCharAt(int index,char ch)


SCJP 6- 91%, IBM DB2, IBM RAD Certified
Divya Sanjeev
Greenhorn

Joined: Dec 16, 2009
Posts: 18
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

Joined: Jun 15, 2010
Posts: 205

you can use
Swastik Dey
Ranch Hand

Joined: Jan 08, 2009
Posts: 990

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.


Swastik
Thakur Sachin Singh
Ranch Hand

Joined: Jun 15, 2010
Posts: 205

your code was so confusing, you can use below code it is very simple.


Divya Sanjeev
Greenhorn

Joined: Dec 16, 2009
Posts: 18
Thank you so much ...Its working fine now
Thakur Sachin Singh
Ranch Hand

Joined: Jun 15, 2010
Posts: 205

Dennis Deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 547
You want every occurrence of 'a' to be replaced by 'ae'. Why not simply use String.replace? What am I missing?


OCPJP 6
 
 
subject: help needed regarding appending character
 
Threads others viewed
RandomAccessFile: backspacing and inserting
a big problem
storing user defined variables in an array
Read an integer line by line
how to get unique address
MyEclipse, The Clear Choice