Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

can i replace only one character from a string?

Status
Not open for further replies.

GoSooJJ

Programmer
Feb 24, 2001
76
US
Hi,
i have this string = "1111111111"
if i want to replace 4th character to '0', how can i do that? i think i can not use replace function for this...
anyone can help?

Thx JJ //
 
You can do something like:

String input = "111111111"
char[] replaced = input.toCharArray();
replaced[3] = '0';
input = new String(replaced);
 
GoSooj,

When dealing with Strings in Java, it's good to thing of the "String" class as an unchangable string of characters. To deal with a string of characters that you can change, you should use the StringBuffer class.

This is the Javadoc description of the StringBuffer class:

A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

Anyway, the code for doing what you want to do would look like this if you chose to use the StringBuffer

Code:
String ones = "111111111";
StringBuffer buffer = new StringBuffer(ones);

buffer.setCharAt(3,'0');

String onesAndZero = buffer.toString();

Hope that helps,
Mike





 
Thank you so much both of u. since i'm new to java your tips are very helpful. Actually, i did different way(not as professional code ^^), but i will convert them to use buffer. thx again.
oh, thx for toCharArray() function too.

JJ //
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top