Change character in string

  • Thread starter Dirk Bruere at NeoPax
  • Start date
A

Arne Vajhøj

Dirk said:
This seems a simple problem but I can't find the method to do it.
How do I set a particular character at a specific index in a string? eg
something like

String.setchar(index, char);

You do not.

But take a look at StringBuilder !

Arne
 
S

Stefan Ram

Dirk Bruere at NeoPax said:
This seems a simple problem but I can't find the method to do it.
How do I set a particular character at a specific index in a string? eg
something like
String.setchar(index, char);

If I remember correctly, it is something like:

public class Main
{
public static void setchar
( final java.lang.String string, final int index, final char ch )
throws java.lang.Throwable
{ final java.lang.reflect.Field field =
java.lang.String.class.getDeclaredField( "value" );
field.setAccessible( true );
java.lang.reflect.Array.setChar( field.get( string ), index, 'x' ); }

public static void main( final java.lang.String[] args )
throws java.lang.Throwable
{ final java.lang.String string = "alpha";
setchar( string, 1, 'x' );
java.lang.System.out.println( string ); }}


But it might not always work, depending on the protection settings.
 
S

Stefan Ram

java.lang.reflect.Array.setChar( field.get( string ), index, 'x' ); }

Change »'x'« to »ch«.

I have modified my program to show that the poor little
string does not know that it has a new hash code now:

public class Main
{
public static void setchar
( final java.lang.String string, final int index, final char ch )
throws java.lang.Throwable
{ final java.lang.reflect.Field field =
java.lang.String.class.getDeclaredField( "value" );
field.setAccessible( true );
java.lang.reflect.Array.setChar( field.get( string ), index, ch ); }

public static void main( final java.lang.String[] args )
throws java.lang.Throwable
{ final java.lang.String string = "alpha";
java.lang.System.out.println( string );
java.lang.System.out.println( string.hashCode() );
setchar( string, 1, 'x' );
java.lang.System.out.println( string );
java.lang.System.out.println( string.hashCode() ); }}

alpha
92909918
axpha
92909918
 
D

Dirk Bruere at NeoPax

Arne said:
http://java.sun.com/javase/6/docs/api/java/lang/String.html

<quote>
Strings are constant; their values cannot be changed after they are
created. String buffers support mutable strings.
</quote>

Arne

PS: Maybe someone at SUN should replace "buffers" with "builders".

Still thinking C++

--
Dirk

http://www.transcendence.me.uk/ - Transcendence UK
http://www.theconsensus.org/ - A UK political party
http://www.onetribe.me.uk/wordpress/?cat=5 - Our podcasts on weird stuff
 
D

Dirk Bruere at NeoPax

Stefan said:
java.lang.reflect.Array.setChar( field.get( string ), index, 'x' ); }

Change »'x'« to »ch«.

I have modified my program to show that the poor little
string does not know that it has a new hash code now:

public class Main
{
public static void setchar
( final java.lang.String string, final int index, final char ch )
throws java.lang.Throwable
{ final java.lang.reflect.Field field =
java.lang.String.class.getDeclaredField( "value" );
field.setAccessible( true );
java.lang.reflect.Array.setChar( field.get( string ), index, ch ); }

public static void main( final java.lang.String[] args )
throws java.lang.Throwable
{ final java.lang.String string = "alpha";
java.lang.System.out.println( string );
java.lang.System.out.println( string.hashCode() );
setchar( string, 1, 'x' );
java.lang.System.out.println( string );
java.lang.System.out.println( string.hashCode() ); }}

alpha
92909918
axpha
92909918

public String insertChar( String commandStr, Char ch, int myIndex)
{
String newString;

StringBuilder builderString = new StringBuilder(commandStr);
builderString.setCharAt(myIndex, ch);
newString = builderString.toString();

return newString;
}

--
Dirk

http://www.transcendence.me.uk/ - Transcendence UK
http://www.theconsensus.org/ - A UK political party
http://www.onetribe.me.uk/wordpress/?cat=5 - Our podcasts on weird stuff
 
A

Arne Vajhøj

Stefan said:
java.lang.reflect.Array.setChar( field.get( string ), index, 'x' ); }

Change »'x'« to »ch«.

I have modified my program to show that the poor little
string does not know that it has a new hash code now:

public class Main
{
public static void setchar
( final java.lang.String string, final int index, final char ch )
throws java.lang.Throwable
{ final java.lang.reflect.Field field =
java.lang.String.class.getDeclaredField( "value" );
field.setAccessible( true );
java.lang.reflect.Array.setChar( field.get( string ), index, ch ); }

public static void main( final java.lang.String[] args )
throws java.lang.Throwable
{ final java.lang.String string = "alpha";
java.lang.System.out.println( string );
java.lang.System.out.println( string.hashCode() );
setchar( string, 1, 'x' );
java.lang.System.out.println( string );
java.lang.System.out.println( string.hashCode() ); }}

alpha
92909918
axpha
92909918

It is a lot worse than that.

public class Main
{
public static void setchar
( final java.lang.String string, final int index, final char ch )
throws java.lang.Throwable
{ final java.lang.reflect.Field field =
java.lang.String.class.getDeclaredField( "value" );
field.setAccessible( true );
java.lang.reflect.Array.setChar( field.get( string ), index, ch ); }

public static void main( final java.lang.String[] args )
throws java.lang.Throwable
{ final java.lang.String string = "alpha";
final java.lang.String string2 = string.substring(0, 3);
java.lang.System.out.println( string );
java.lang.System.out.println( string.hashCode() );
setchar( string, 1, 'x' );
java.lang.System.out.println( string );
java.lang.System.out.println( string.hashCode() );
java.lang.System.out.println( string2 );}}

Arne
 
L

Lew

Dirk said:
This seems a simple problem but I can't find the method to do it.
How do I set a particular character at a specific index in a
string? eg [sic] something like

String.setchar(index, char);

Others have given good answers. Note, however, that if such a method did
exist it would not be static, and 'char', being a keyword, would not be a
valid variable name.

Alternative approach:

String orig = getValue();
char repl = getReplacement();
String replaced =
orig.substring( 0, index )
+ repl
+ orig.substring( index + 1 );

Also, if you want to replace every occurrence of a particular character with a
given replacement character, there's
<http://java.sun.com/javase/6/docs/api/java/lang/String.html#replace(char, char)>
 
A

Arne Vajhøj

Peter said:
Or, perhaps just add "and builders". Or maybe state the actual class
names, "StringBuffer" and "StringBuilder". Before StringBuilder came
along in 1.5, StringBuffer was the way to mutate a string.

There are little reason to have 1.6 docs reflect pre-1.5.

And since:
http://java.sun.com/javase/6/docs/api/java/lang/StringBuffer.html
state:

<quote>
The StringBuilder class should generally be used in preference to this
one, as ...
</quote>

Then it should be either "string builder" or "string builder (or string
buffer)" to properly reflect what is recommended. Or actual class names.

Arne
 
R

Roedy Green

This seems a simple problem but I can't find the method to do it.
How do I set a particular character at a specific index in a string? eg
something like

String.setchar(index, char);

all you can do is create a new string with a character changed,
usually done with a StringBuilder, or possibly with a char[ ].

see http://mindprod.com/jgloss/stringbuilder.html
--
Roedy Green Canadian Mind Products
http://mindprod.com

"Pollution is nothing but the resources we are not harvesting. We allow them to disperse because we’ve been ignorant of their value."
~ Richard Buckminster (Bucky) Fuller
 
A

Arne Vajhøj

Peter said:
About as much reason to exclude mention of pre-1.5 classes.

Nonsense.

There is good reason to mention what is recommended in current
version.

There is very little reason to mention what is not receommended.
The docs
would be pretty hard to follow if we just went around removing
everything that mentioned something that existed prior to 1.5.

True.

But irrelevant.

I did not suggest removing references to everything
that existed before - I suggested removing references to
everything that has been replaced with new stuff.
Whatever. Neither you nor I get to say what goes in the docs anyway, so
debating the exact wording is pointless.

Did you join usenet yesterday ????

Opinions about how things out of the participants control should
be is a pretty big chunk of usenet.
The fact is, there's a
legitimate reason that the text said "buffers".

Only if the intention is to lure people to use the old classes
instead of the new.

Which is not legit in my opinion.
And you can still use
StringBuffer for the purpose (note that the StringBuffer class hasn't
been deprecated).

Not deprecated as in @Deprecated, but deprecated like Vector is.
All I did was offer some _additional_ possible wordings, to go along
with yours. It's not like I was saying your suggestion wasn't
acceptable. There's no reason to get argumentative about it.

There is an important point in emphasizing that StringBuilder
is what people should be using - not StringBuffer.

It is over 10 years since ArrayList showed up and we still
occasionally see Vector.

If StringBuffer is to be out before 2020, then some consistency
is needed.

Arne
 
L

Lew

Peter said:
Right. As in "still useful". One difference in particular is that both
are thread-safe, whereas their replacements are not. In certain cases,
that would be important.

First of all, 'Vector' is only "thread-safe" in a very limited sense.
Secondly, it has an equally thread-safe replacement that is a true collections
class, 'Collections.synchronizedList( someList )'. Ergo, no reason to use the
obsolete and crufty 'Vector' class. The 'synchronizedList' technique has
additional advantages, such as finer-grained control over the performance
characteristics of the list.

One should avoid using 'java.util.Vector' and 'java.util.Hashtable' in favor
of their better replacements. It's been over ten years, for Pete's sake!
They're obsolete. Move on.

Except for interaction with old APIs that were built with 'Vector' or
'Hashtable' before 1998, I can think of no advantage to make those dinosaurs
"still useful".
 
L

Lew

[...]
Except for interaction with old APIs that were built with 'Vector' or  
'Hashtable' before 1998, I can think of no advantage to make those  
dinosaurs "still useful".

Straw man.  There need not be an "advantage" for something to be "still  
useful".

My twenty-year-old car provides zero _advantage_ over a brand new car.  
But it's absolutely still useful.  There's no reason for me to "deprecate"  
it as long as it continues to serve its purpose.

Eschew 'Vector' and 'Hashtable' in favor of the more modern
equivalents that have greater flexibility and do not sport extraneous
features.
 
A

Andreas Leitgeb

Lew said:
Eschew 'Vector' and 'Hashtable' in favor of the more modern
equivalents that have greater flexibility and do not sport extraneous
features.

sport? I guess you mean support, but was it a typo or some
(yet unknown to me) english idiom?

In most people's mindset, "do not s[up]port extraneous features"
is taken negative, not positive. Not everyone is follower of
Occam w.r.t choice of his tools.

PS:
Most of the times, one doesn't need a synchronized collection,
or has to explicitly synchronize it on some other Object, anyway.
Then it is correct, to discourage use of Vector. Otherwise it's
no worse than a Collections.synchronizedList(new ArrayList())
(but less fuss to create).

In contrast to an old car, which often burns more fuel for less
power than a modern one, old Vector is just as good as the modern
ones (once made synchronized, too), disregarding Occam's razor.
 
L

Lew

sport?  I guess you mean support, but was it a typo or some
(yet unknown to me) english idiom?

No, I meant "sport", not a typo, not an idiom but a literal meaning.
I recommend Merriam Webster:
<http://www.merriam-webster.com/dictionary/sport[1]>
Transitive verb meaning 1.

Or, if you prefer, Wiktionary:
<http://en.wiktionary.org/wiki/sport#Verb>
Verb, meaning 3.

If a word is somewhat unfamiliar, I find the dictionary to be very
useful.
In most people's mindset, "do not s[up]port extraneous features"
is taken negative, not positive. Not everyone is follower of
Occam w.r.t choice of his tools.

Why would you want extra methods that duplicate collections methods
but that you don't use? Why would you want Enumeration when you only
use Iterator? It's just extra cruft that you don't need.
PS:
Most of the times, one doesn't need a synchronized collection,
or has to explicitly synchronize it on some other Object, anyway.
Then it is correct, to discourage use of Vector.  Otherwise it's
no worse than a  Collections.synchronizedList(new ArrayList())
(but less fuss to create).

Yes, it is worse, in that it's less flexible.
In contrast to an old car, which often burns more fuel for less
power than a modern one, old Vector is just as good as the modern
ones (once made synchronized, too), disregarding Occam's razor.

Why do you disregard Occam's razor?

The point is that Vector and Hashtable are obsolete, have extraneous
weight that isn't needed and doesn't fit into the Collections
framework, and isn't as flexible as the more modern alternatives.
 
W

wim

Op 10-03-09 01:48, schreef Dirk Bruere at NeoPax:
This seems a simple problem but I can't find the method to do it.
How do I set a particular character at a specific index in a string? eg
something like

String.setchar(index, char);
String is immutable, like Integer, Double and some others.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Can an Applet beep? 4
ListModel name 10
Sorting a JList 4
JMF? 21
Slightly tricky string problem 18
Java in Java 10
Official Java Classes 10
File over network timeout 3

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,738
Latest member
JinaMacvit

Latest Threads

Top