String Manipulation Problem

A

Anony!

Hi

<code snippet>

public String manipulator(String s)
{
String str "";
for (int i=s.length()-1; i>0; i--)
{
str = str + s.charAt(i);

if (str.charAt(i) == 'a')
str.charAt(i) = 't'; //doesnt like this
}
return str;
}

trying to replace a character ('a') in a string to a character ('t').
i thought about using the string replace() method, but i realise that i dont
wont to replace all occurences of a character with another - just a single
event.

Thanks in advance

AaA
 
A

Anony!

"Anony!"
Hi

<code snippet>

public String manipulator(String s)
{
String str "";
for (int i=s.length()-1; i>0; i--)
{
str = str + s.charAt(i);

if (str.charAt(i) == 'a')
str.charAt(i) = 't'; //doesnt like this
}
return str;
}

trying to replace a character ('a') in a string to a character ('t').
i thought about using the string replace() method, but i realise that i dont
wont to replace all occurences of a character with another - just a single
event.

Thanks in advance

AaA

Nevermind. I worked it out using StringBuffer class.

I wonder why the string class doesn't have the method setCharAt() method!

The stringbuffer class can do whatever the string class can, but more!

AaA
 
A

Andy Fish

a string object is immutable meaning it cannot be changed. that's a
fundamental part of the language
 
A

Andrew Thompson

<top-posting corrected, trimming applied>

(Anony!) ...
well that explains why it isnt in the string class.

Also mentioned in the API docs for String (second par.)
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html

The API docs also mention many other
important things, I consult them daily.

For a 'slim' intro to the JDocs, try
<http://java.sun.com/j2se/1.5.0/docs/api/overview-summary.html>
But if you are feeling brave, have broadband
and are not using IE, you might also try..
<http://java.sun.com/j2se/1.5.0/docs/api/>

For convenience, you can get to the 1.4/1.5 class
and package docs (as well as the source) from here..
<http://www.physci.org/api.jsp> like
<http://www.physci.org/api.jsp?class=java.lang.String>

HTH
 
R

Roedy Green

str.charAt(i) = 't'; //doesnt like this

This is not PL/1, no pseudovariables.

Further, Strings are immutable. see
http://mindprod.com/jgloss/immutable.html

Look at the code in src.zip for replace.

You will likely see it works like this:

Use indexOf to see if there are any instances of the replaceable char.
If not, return the original String.

Is so, create a StringBuffer the same length as the String.
Then look, looking at each char with charAt, and if it is not the
replaceable char, append to the StringBuffer. If it is, replace it.
When done, return sb.toString().

Make the modification that when you find a replaceable char, copy the
rest of the string to the StringBuffer using substring and append.
 
A

Andrew Thompson

...
out of interest, why do you say "not using IE" - I can seem to access this
URL fine from IE

The Sun 1.4.2 JavaDocs/my box/IE don't play well
together, IE chokes, utters a few gurgling sounds,
then closes itself and all other IE windows that
are open*. The 1.5.0 docs are bigger.

* Mozilla on the same PC handles the docs just fine.

It is probably a bizarre combination of factors
affecting only this, rather hacked together, PC
I am using.

OTOH, I won't let that stop me revelling in the
deficiencies of the insecure, standards trashing
'operating system component' that has been the
bane of Java (and web) developers for years..

[ It is one of those -
"Don't get me started!" things.. ;-) ]
 
L

Liz

Anony! said:
Ok, but that doesnt explain the method replace() in String class, which does
modifies a string.
not true, from the documentation
.....\docs\api\java\lang\String.html
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.
 
R

Roedy Green

Ok, but that doesnt explain the method replace() in String class, which does
modifies a string.

No it does not. It create a new String object and leaves the original
unmodified.

You can prove it with:

String a = "peal";
String b = a.replace( 'a', 'e' );

System.out.println( a );

System.out.println( b );
 
T

Tony Morris

Ok, but that doesnt explain the method replace() in String class, which
does
modifies a string.

You seem to misunderstand something (JLS 3.10.5 to be precise).
Try proving this to yourself.
You can do this with

class X {
public static void main(String[] args) {
String s = args[0];
// Try making this output...
System.out.println(s);
method(s);
// different to this output.
// If you can, you have proven that Strings are mutable.
System.out.println(s);
}

private static void method(String s) {
// You can do whatever you like in here.
// including using the replace() method
// Try to mute the String using whatever you feel obliged to use.
}
}

*Note that there is a way of "muting a String", but it is completely
unrelated to the demonstrated lack of understanding, and so it would be
beneficial of the poster remains ignorant to it
(http://www.xdweb.net/~dibblego/java/trivia/answers.html#q1)
 
A

Anony!

not true, from the documentation
....\docs\api\java\lang\String.html
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.

Ok. My problem is that I don't examine the API docs closely enough. I tend
to skim read.

Thanks

AaA
 
T

Tor Iver Wilhelmsen

Liz said:
Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.

Yes,. but it's still bad form on Sun's side to have non-static methods
in an immutable class that by their very name and existance can fool
people into thinking it modifies the object.

It should have been something like

static String copyAndReplace(String orig, ...)

either in String or a related StringUtils class.
 
T

Tony Morris

Yes,. but it's still bad form on Sun's side to have non-static methods
in an immutable class that by their very name and existance can fool
people into thinking it modifies the object.

Are you arguing that any method name that is not self-documenting is poor
form?
Or, are you arguing that a method that might make some implication about a
potential misinterpretation if it is assumed that it is self-documenting is
poor form?
I disagree on both counts.

Methods generally should be self-documenting, but there are times when it is
unreasonable.

String
replaceButNotModifyTheObjectIfYouStillDontUnderstandWhatThisMeansEvenAfterRe
adingTheAPISpecificationTooBadYoureOnYourOwn(String s)
It should have been something like

static String copyAndReplace(String orig, ...)

There is:
static String copyValueOf(char[])
static String copyValueOf(char[], int, int)
 
T

Tor Iver Wilhelmsen

Tony Morris said:
Are you arguing that any method name that is not self-documenting is poor
form?

No, I am talking about _instance_ methods that actually don't operate
on the _instance_ is bad form.
Or, are you arguing that a method that might make some implication
about a potential misinterpretation if it is assumed that it is
self-documenting is poor form?

"Self-documentation" does not enter into the picture; though it would
have helped that a method called "replace" had consistent
interpretation between classes.

As for documentation, apparently the writers of replace(CharSequence,
CharSequence) didn't bother to read the replace(char, char) docs -
that method's docs does not bother to indicate (except in the return
clause) that it doesn't actually change the object.
 
M

Michael Borgwardt

Tor said:
No, I am talking about _instance_ methods that actually don't operate
on the _instance_ is bad form.

But the method *does* operate on the instance, just not by mutating it.
 
R

Roedy Green

Methods generally should be self-documenting, but there are times when it is
unreasonable.

There are certain base presumptions that you need to know. These need
not be retaught in every method name.

So, for example, we all know that methods never modify the caller's
parameters.

We know that immutable object fields are never modified.

It would be silly to belabour these points in production code used by
professional programmers. It would make the code less
readable/maintainable and confusingly imply the opposite could exist.
 

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

Members online

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top