Java Forum / First Aid / April 2004
delete a char from string ?
ssaa - 14 Apr 2004 07:40 GMT 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.
Adam - 14 Apr 2004 10:44 GMT > Hi, > [quoted text clipped - 5 lines] > 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 - 14 Apr 2004 11:54 GMT > 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 - 14 Apr 2004 13:40 GMT > Hi, > [quoted text clipped - 9 lines] > > 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); }
 Signature Josef Garvi
"Reversing desertification through drought tolerant trees" http://www.eden-foundation.org/
new income - better environment - more food - less poverty
Steve W. Jackson - 14 Apr 2004 17:00 GMT >:ssaa wrote: >: [quoted text clipped - 22 lines] >: 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 =
 Signature Steve W. Jackson Montgomery, Alabama
Daniel Sjöblom - 14 Apr 2004 19:04 GMT >>:ssaa wrote: >>: [quoted text clipped - 24 lines] > > 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 =
 Signature Daniel Sjöblom Remove _NOSPAM to reply by mail
Steve W. Jackson - 14 Apr 2004 21:19 GMT >:Steve W. Jackson wrote: >:> In article <c5jbe8$2962v$1@ID-194406.news.uni-berlin.de>, [quoted text clipped - 67 lines] >:> >:> = 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 =
 Signature Steve W. Jackson Montgomery, Alabama
Daniel Sjöblom - 14 Apr 2004 23:04 GMT > Your new method is definitely better than the indexOf, but I stand by > what I said about *generally* not using concatenation, particularly in [quoted text clipped - 5 lines] > 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.)
 Signature Daniel Sjöblom Remove _NOSPAM to reply by mail
Tony Morris - 22 Apr 2004 12:28 GMT > 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.
 Signature Tony Morris (BInfTech, Cert 3 I.T., SCJP[1.4], SCJD) Software Engineer IBM Australia - Tivoli Security Software (2003 VTR1000F)
Roedy Green - 22 Apr 2004 18:15 GMT >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.
Jeff - 15 Apr 2004 07:52 GMT 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.
> Hi, > [quoted text clipped - 9 lines] > > Thanks alot. Squanderette - 15 Apr 2004 14:31 GMT > Could be done with C++ in two lines: > string::iterator new_end = remove(formula.begin(), formula.end(), '['); [quoted text clipped - 15 lines] > > > > Thanks alot. You could use the String form: String f = formulla.replaceAll("\\[", ""));
Need to escape the "[" because it's a special character (in a regular expression)
 Signature Squanderette "What is this life, if full of care, We have no time to stand and stare ..."
Roedy Green - 22 Apr 2004 06:23 GMT >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.
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|