Home > Archive > Java Help > April 2004 > delete a char from string ?
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
delete a char from string ?
|
|
|
| Hi,
I want to delete a char from string. i used the following function.
String f = formulla.replace('[','');
The above function doesnt work as it tells me to put a space or some
char in 2nd parameter which i dont want. i just want to delete all
occurences of some specific char in a string.
Any suggestion.
Thanks alot.
| |
|
|
"ssaa" <ssaa@hotmail.com> wrote in message
news:407CDCE7.7070108@hotmail.com...
> Hi,
>
> I want to delete a char from string. i used the following function.
>
> String f = formulla.replace('[','');
>
> The above function doesnt work as it tells me to put a space or some
> char in 2nd parameter which i dont want. i just want to delete all
> occurences of some specific char in a string.
public class CharDeleting
{
public static void main(String[] args)
{
System.out.println( deleteChar("Get rid of this #hash" ,
'#') );
}
static String deleteChar(String text, int chr)
{
int index = text.indexOf(chr);
String retval = text.substring(0,index);
if(index<text.length()-1) retval = retval +
text.substring(index+1);
return retval;
}
}
Some conditions should be added (what if text == null, chr is not in
text, chr is at the beginning of text, etc. )
Adam
| |
| Bjorn Abelli 2004-04-14, 7:32 am |
| ssaa wrote:
> I want to delete a char from string. i used
> the following function.
>
> String f = formulla.replace('[','');
> The above function doesnt work as it tells me
> to put a space or some char in 2nd parameter
> which i dont want.
As characters are primitive types, there's no such thing as an "empty" char.
One possible approach is to use replaceAll instead that works with Strings
(and Strings can be empty), but note that it works in a different way, as it
makes use of regex.
Say for example that you wanted to "delete" all occurences of the character
'a' in a string, you could use:
String f = formulla.replaceAll("a","");
However, as replaceAll is using regex, special characters such as [ must be
treated in a special way.
String f = formulla.replaceAll("\\[","");
The special format in this case is because [ is a special character in
regex, which must be preceeded by a \ to be treated as a character, and as a
\ is a special character in strings, that in itself must be preceeded by
another \
Anyway, it works...
// Bjorn A
| |
| Josef Garvi 2004-04-14, 9:36 am |
| ssaa wrote:
> Hi,
>
> I want to delete a char from string. i used the following function.
>
> String f = formulla.replace('[','');
>
> The above function doesnt work as it tells me to put a space or some
> char in 2nd parameter which i dont want. i just want to delete all
> occurences of some specific char in a string.
>
> Any suggestion.
>
> Thanks alot.
Convert to a StringBuffer.
public static void main(String[] args) {
String s = "abc[d[ef";
StringBuffer sb = new StringBuffer(s);
while (sb.indexOf("[") >= 0)
sb.deleteCharAt(sb.indexOf("["));
s = new String(sb);
System.out.println(s);
}
--
Josef Garvi
"Reversing desertification through drought tolerant trees"
http://www.eden-foundation.org/
new income - better environment - more food - less poverty
| |
| Daniel Sjöblom 2004-04-14, 3:38 pm |
| Steve W. Jackson wrote:
> In article <c5jbe8$2962v$1@ID-194406.news.uni-berlin.de>,
> Josef Garvi <josef@eden-foundation.org> wrote:
>
>
>
>
> Far more efficient, IMHO, than an earlier response using concatenation.
There is no IMO when discussing the speeds of algorithms. Only proofs
and benchmarks.
Actually, concatenation is usually much faster since you can't just stab
a hole in some memory without moving the remaining characters over the
'hole'. When concatenating, you copy at most n characters, where n is
the number of characters in the original String, so the algorithm has
O(n) running time. When deleting, worst case scenario is O(n*n)
(basically (n-1) + (n-2) + ... + 1 which is something like n*n - 2n + 1
- n*n/2, by some quick math) which is a lot worse.
And the above implementation is suboptimal anyway, calling indexOf
multiple times and using String instead of char as the argument to
indexOf. Try this instead:
static String deleteChar(String str, char c)
{
final int len = str.length();
StringBuffer buff = new StringBuffer(len);
int mark = 0;
int pos = 0;
while ((pos = str.indexOf(c, pos)) != -1)
{
buff.append(str.substring(mark, pos));
mark = ++pos;
}
buff.append(str.substring(mark, len));
return buff.toString();
}
> But there's one thing I would change. Instead of "new String(sb)",
> simply use "sb.toString()".
>
> = Steve =
--
Daniel Sjöblom
Remove _NOSPAM to reply by mail
| |
| Steve W. Jackson 2004-04-14, 5:34 pm |
| In article <407d89fa$0$23095$7b6a8dc4@news.mbnet.fi>,
Daniel Sjöblom <dsjoblom@mbnet.fi_NOSPAM> wrote:
>:Steve W. Jackson wrote:
>:> In article <c5jbe8$2962v$1@ID-194406.news.uni-berlin.de>,
>:> Josef Garvi <josef@eden-foundation.org> wrote:
>:>
>:>
>:>>:ssaa wrote:
>:>>:
>:>>:> Hi,
>:>>:>
>:>>:> I want to delete a char from string. i used the following function.
>:>>:>
>:>>:> String f = formulla.replace('[','');
>:>>:>
>:>>:> The above function doesnt work as it tells me to put a space or some
>:>>:> char in 2nd parameter which i dont want. i just want to delete all
>:>>:> occurences of some specific char in a string.
>:>>:>
>:>>:> Any suggestion.
>:>>:>
>:>>:> Thanks alot.
>:>>:
>:>>:Convert to a StringBuffer.
>:>>:
>:>>: public static void main(String[] args) {
>:>>: String s = "abc[d[ef";
>:>>: StringBuffer sb = new StringBuffer(s);
>:>>: while (sb.indexOf("[") >= 0)
>:>>: sb.deleteCharAt(sb.indexOf("["));
>:>>: s = new String(sb);
>:>>: System.out.println(s);
>:>>: }
>:>
>:>
>:> Far more efficient, IMHO, than an earlier response using concatenation.
>:
>:There is no IMO when discussing the speeds of algorithms. Only proofs
>:and benchmarks.
>:
>:Actually, concatenation is usually much faster since you can't just stab
>:a hole in some memory without moving the remaining characters over the
>:'hole'. When concatenating, you copy at most n characters, where n is
>:the number of characters in the original String, so the algorithm has
>:O(n) running time. When deleting, worst case scenario is O(n*n)
>:(basically (n-1) + (n-2) + ... + 1 which is something like n*n - 2n + 1
>:- n*n/2, by some quick math) which is a lot worse.
>:
>:And the above implementation is suboptimal anyway, calling indexOf
>:multiple times and using String instead of char as the argument to
>:indexOf. Try this instead:
>:
>:static String deleteChar(String str, char c)
>:{
>: final int len = str.length();
>: StringBuffer buff = new StringBuffer(len);
>:
>: int mark = 0;
>: int pos = 0;
>:
>: while ((pos = str.indexOf(c, pos)) != -1)
>: {
>: buff.append(str.substring(mark, pos));
>: mark = ++pos;
>: }
>:
>: buff.append(str.substring(mark, len));
>:
>: return buff.toString();
>:}
>:
>:> But there's one thing I would change. Instead of "new String(sb)",
>:> simply use "sb.toString()".
>:>
>:> = Steve =
Your new method is definitely better than the indexOf, but I stand by
what I said about *generally* not using concatenation, particularly in
Sun's implementation of the JVM. Look at how they actually implement
string + string and you'll find that it entails creating a new
StringBuffer, doing an append operation, then using toString. When you
do that repeatedly in a loop (unless you can guarantee a very short
string), you're creating lots of short-lived objects needlessly.
There's more to consider than just speed -- since the fastest machine
will become a doorstop when it runs out of memory and terminates the JVM.
= Steve =
--
Steve W. Jackson
Montgomery, Alabama
| |
|
| Could be done with C++ in two lines:
string::iterator new_end = remove(formula.begin(), formula.end(), '[');
formula.erase(new_end, formula.end());
And it would be about very efficient.
ssaa <ssaa@hotmail.com> wrote in message news:<407CDCE7.7070108@hotmail.com>...
> Hi,
>
> I want to delete a char from string. i used the following function.
>
> String f = formulla.replace('[','');
>
> The above function doesnt work as it tells me to put a space or some
> char in 2nd parameter which i dont want. i just want to delete all
> occurences of some specific char in a string.
>
> Any suggestion.
>
> Thanks alot.
| |
| Squanderette 2004-04-15, 10:35 am |
| "Jeff" <surferjeff@gmail.com> wrote in message
news:781dd16f.0404142252.7da3cf76@posting.google.com...
> Could be done with C++ in two lines:
> string::iterator new_end = remove(formula.begin(), formula.end(), '[');
> formula.erase(new_end, formula.end());
>
> And it would be about very efficient.
>
> ssaa <ssaa@hotmail.com> wrote in message
news:<407CDCE7.7070108@hotmail.com>...[color=darkred]
You could use the String form:
String f = formulla.replaceAll("\\[", ""));
Need to escape the "[" because it's a special character (in a regular
expression)
--
Squanderette
"What is this life, if full of care,
We have no time to stand and stare ..."
| |
| Steve W. Jackson 2004-04-17, 2:32 am |
| In article <c5jbe8$2962v$1@ID-194406.news.uni-berlin.de>,
Josef Garvi <josef@eden-foundation.org> wrote:
>:ssaa wrote:
>:
>:> Hi,
>:>
>:> I want to delete a char from string. i used the following function.
>:>
>:> String f = formulla.replace('[','');
>:>
>:> The above function doesnt work as it tells me to put a space or some
>:> char in 2nd parameter which i dont want. i just want to delete all
>:> occurences of some specific char in a string.
>:>
>:> Any suggestion.
>:>
>:> Thanks alot.
>:
>:Convert to a StringBuffer.
>:
>: public static void main(String[] args) {
>: String s = "abc[d[ef";
>: StringBuffer sb = new StringBuffer(s);
>: while (sb.indexOf("[") >= 0)
>: sb.deleteCharAt(sb.indexOf("["));
>: s = new String(sb);
>: System.out.println(s);
>: }
Far more efficient, IMHO, than an earlier response using concatenation.
But there's one thing I would change. Instead of "new String(sb)",
simply use "sb.toString()".
= Steve =
--
Steve W. Jackson
Montgomery, Alabama
| |
| Daniel Sjöblom 2004-04-18, 9:44 pm |
| Steve W. Jackson wrote:
> Your new method is definitely better than the indexOf, but I stand by
> what I said about *generally* not using concatenation, particularly in
> Sun's implementation of the JVM. Look at how they actually implement
> string + string and you'll find that it entails creating a new
> StringBuffer, doing an append operation, then using toString. When you
> do that repeatedly in a loop (unless you can guarantee a very short
> string), you're creating lots of short-lived objects needlessly.
> There's more to consider than just speed -- since the fastest machine
> will become a doorstop when it runs out of memory and terminates the JVM.
Oh, you are right about that. I didn't actually notice that the method
posted used the string concatenation operator (+). That should
definitely be avoided in any performance sensitive code. I was talking
about generic concatenation (StringBuffer.append() in the example I gave.)
--
Daniel Sjöblom
Remove _NOSPAM to reply by mail
| |
| Roedy Green 2004-04-22, 2:38 am |
| On Thu, 15 Apr 2004 14:31:02 +0100, "Squanderette"
<jdbr20766@SPAM.TRAP.blueyonder.co.uk> wrote or quoted :
>String f = formulla.replaceAll("\\[", ""));
Watch out with this. The first parameter is not a simple String to
search for. It is a Regex Pattern.
See http://mindprod.com/jgloss/regex.html
--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
| |
| Tony Morris 2004-04-22, 8:37 am |
| > Oh, you are right about that. I didn't actually notice that the method
> posted used the string concatenation operator (+). That should
> definitely be avoided in any performance sensitive code. I was talking
> about generic concatenation (StringBuffer.append() in the example I gave.)
Incorrect.
The impacts of its use should be considered in performance critical
applications.
The impact may be nothing, to minimal to extraordinarily ridiculous
depending on a number of factors.
Obviously, with respect to compile-time constants, there is no effect on
runtime performance.
The other factors generally include how runtime optimisation has been
implemented.
Therefore, it is not strictly correct to suggest that the String
concatenation operator has performance problems.
This is a runtime and compiler implementation fault that is intended to be
rectified.
--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
| |
| Roedy Green 2004-04-22, 2:51 pm |
| On Thu, 22 Apr 2004 11:28:24 GMT, "Tony Morris" <not@telling.you>
wrote or quoted :
>Therefore, it is not strictly correct to suggest that the String
>concatenation operator has performance problems.
Perhaps what he should have said is:
concatenation is implemented by creating a stringbuffer, appending and
converting to string usually at least once per statement involving
concatenation. If you roll your own, you can usually avoid the
overhead of creating a stringbuffer and converting to string except at
the beginning and end of a series of statements involving
concatenation.
Normally you would never even think about the difference unless it
were in a loop.
--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
|
|
|
|
|