File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes help needed regarding appending character Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
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: 232

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: 232

you can use
Swastik Dey
Rancher

Joined: Jan 08, 2009
Posts: 1449
    
    6

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: 232

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: 232

dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
You want every occurrence of 'a' to be replaced by 'ae'. Why not simply use String.replace? What am I missing?
 
 
subject: help needed regarding appending character
 
Similar Threads
a big problem
RandomAccessFile: backspacing and inserting
Read an integer line by line
storing user defined variables in an array
how to get unique address