Doing minus operation on string - java

I have a small problem with the minus operation in java. When the user press the 'backspace' key, I want the char the user typed, to be taken away from the word which exists.
e.g
word = myname
and after one backspace
word = mynam
This is kinda of what I have:
String sentence = "";
char c = evt.getKeyChar();
if(c == '\b') {
sentence = sentence - c;
} else {
sentence = sentence + c;
}
The add operation works. So if I add a letter, it adds to the existing word. However, the minus isn't working. Am I missing something here? Or doing it completely wrong?

Strings don’t have any kind of character subtraction that corresponds to concatenation with the + operator. You need to take a substring from the start of the string to one before the end, instead; that’s the entire string except for the last character. So:
sentence = sentence.substring(0, sentence.length() - 1);

For convenience, Java supports string concatenation with the '+' sign. This is the one binary operator with a class type as an operand. See String concatenation operator in the Java Language Specification.
Java does not support an overload of the '-' operator between a String and a char.
Instead, you can remove a character from a string by adding the substrings before and after.

sentance = sentance.substring(0, sentance.length() - 1);
There is no corresponding operator to + which allows you to delete a character from a String.

You should investigate the StringBuilder class, eg:
StringBuilder sentence = new StringBuilder();
Then you can do something like:
sentence.append(a);
for a new character or
sentence.deleteCharAt(sentence.length() - 1);
Then when you actually want to use the string, use:
String s = sentence.toString();

Related

How can I add a character inside a Regular Expression which changes each time?

String s = scan.nextLine();
s = s.replaceAll(" ", "");
for (int i = 0; i < s.length(); i++) {
System.out.print(s.charAt(i) + "-");
int temp = s.length();
// this line is the problem
s = s.replaceAll("[s.charAt(i)]", '');
System.out.print((temp - s.length()) + "\n");
i = -1;
}
I was actually using the above method to count each character.
I wanted to use s.charAt(i) inside Regular Expression so that it counts and displays as below. But that line (line 10) doesn't work I know.
If it's possible how can I do it?
Example:
MALAYALAM (input)
M-2
A-4
L-2
Y-1
Java does not have string interpolation, so code written inside a string literal will not be executed; it is just part of the string. You would need to do something like "[" + s.charAt(i) + "]" instead to build the string programmatically.
But this is problematic when the character is a regex special character, for example ^. In this case the character class would be [^], which matches absolutely any character. You could escape regex special characters while building the regex, but this is overly complicated.
Since you just want to replace occurrences an exact substring, it is simpler to use the replace method which does not take a regex. Don't be fooled by the name replace vs. replaceAll; both methods replace all occurrences, the difference is really that replaceAll takes a regex but replace just takes an exact substring. For example:
> "ababa".replace("a", "")
"bb"
> "ababa".replace("a", "c")
"cbcbc"

Correct way to trim a string in Java

In Java, I am doing this to trim a string:
String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.trim();
System.out.println("after->>"+input+"<<-");
Output is:
before->> some Thing <<-
after->>some Thing<<-
Works. But I wonder if by assigning a variable to itself, I am doing the right thing. I don't want to waste resources by creating another variable and assigning the trimmed value to it. I would like to perform the trim in-place.
So am I doing this right?
You are doing it right. From the documentation:
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.
Also from the documentation:
trim
public String trim()
Returns a copy of the string, with leading and trailing whitespace
omitted. If this String object represents an empty character sequence,
or the first and last characters of character sequence represented by
this String object both have codes greater than '\u0020' (the space
character), then a reference to this String object is returned.
Otherwise, if there is no character with a code greater than '\u0020'
in the string, then a new String object representing an empty string
is created and returned.
Otherwise, let k be the index of the first character in the string
whose code is greater than '\u0020', and let m be the index of the
last character in the string whose code is greater than '\u0020'. A
new String object is created, representing the substring of this
string that begins with the character at index k and ends with the
character at index m-that is, the result of this.substring(k, m+1).
This method may be used to trim whitespace (as defined above) from the
beginning and end of a string.
Returns:
A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white
space.
As strings in Java are immutable objects, there is no way to execute trimming in-place. The only thing you can do to trim the string is create new trimmed version of your string and return it (and this is what the trim() method does).
In theory you are not assigning a variable to itself. You are assigning the returned value of method trim() to your variable input.
In practice trim() method implementation is optimized so that it is creating (and returning) another variable only when necessary. In other cases (when there is actually no need to trim) it is returning a reference to original string (in this case you are actually assigning a variable to itself).
See http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.trim%28%29
Anyway trim() does not modify original string, so this is the right way to use it.
String::strip…
The old String::trim method has a strange definition of whitespace.
As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.
Example code.
String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");
Or you can strip just the leading or just the trailing whitespace.
The traditional approach is to use the trim method inline...for example:
String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
System.out.println("after->>"+input.trim()+"<<-");
If it is a string that should be trimmed for all usages, trim it up front like you have done. Re-using the same memory location like you have done is not a bad idea, if you want to communicate your intent to other developers. When writing in Java, memory managment is not they key issue since the "gift" of Java is that you do not need to manage it.
Yes, but there will still be two objects until the garbage collector removes the original value that input was pointing to. Strings in Java are immutable. Here is a good explanation: Immutability of Strings in Java.
If we have to trim a String without using trim(), split() methods of Java then following source code can be helpful.
static String allTrim(String str)
{
int j = 0;
int count = 0; // Number of extra spaces
int lspaces = 0;// Number of left spaces
char ch[] = str.toCharArray();
int len = str.length();
StringBuffer bchar = new StringBuffer();
if(ch[0] == ' ')
{
while(ch[j] == ' ')
{
lspaces++;
j++;
}
}
for(int i = lspaces; i < len; i++)
{
if(ch[i] != ' ')
{
if(count > 1 || count == 1)
{
bchar.append(' ');
count = 0;
}
bchar.append(ch[i]);
}
else if(ch[i] == ' ')
{
count++;
}
}
return bchar.toString();
}
The java string trim() method eliminates leading and trailing spaces
public class StringTrimExample{
public static void main(String args[]){
String s1=" hello string ";
System.out.println(s1+"javatpoint");//without trim()
System.out.println(s1.trim()+"javatpoint");//with trim()
}}
output
hello string javatpoint
hello stringjavatpoint

Remove Special Characters For A Pattern Java

I want to remove that characters from a String:
+ - ! ( ) { } [ ] ^ ~ : \
also I want to remove them:
/*
*/
&&
||
I mean that I will not remove & or | I will remove them if the second character follows the first one (/* */ && ||)
How can I do that efficiently and fast at Java?
Example:
a:b+c1|x||c*(?)
will be:
abc1|xc*?
This can be done via a long, but actually very simple regex.
String aString = "a:b+c1|x||c*(?)";
String sanitizedString = aString.replaceAll("[+\\-!(){}\\[\\]^~:\\\\]|/\\*|\\*/|&&|\\|\\|", "");
System.out.println(sanitizedString);
I think that the java.lang.String.replaceAll(String regex, String replacement) is all you need:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String).
there is two way to do that :
1)
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("+");
arrayList.add("-");
arrayList.add("||");
arrayList.add("&&");
arrayList.add("(");
arrayList.add(")");
arrayList.add("{");
arrayList.add("}");
arrayList.add("[");
arrayList.add("]");
arrayList.add("~");
arrayList.add("^");
arrayList.add(":");
arrayList.add("/");
arrayList.add("/*");
arrayList.add("*/");
String string = "a:b+c1|x||c*(?)";
for (int i = 0; i < arrayList.size(); i++) {
if (string.contains(arrayList.get(i)));
string=string.replace(arrayList.get(i), "");
}
System.out.println(string);
2)
String string = "a:b+c1|x||c*(?)";
string = string.replaceAll("[+\\-!(){}\\[\\]^~:\\\\]|/\\*|\\*/|&&|\\|\\|", "");
System.out.println(string);
Thomas wrote on How to remove special characters from a string?:
That depends on what you define as special characters, but try
replaceAll(...):
String result = yourString.replaceAll("[-+.^:,]","");
Note that the ^ character must not be the first one in the list, since
you'd then either have to escape it or it would mean "any but these
characters".
Another note: the - character needs to be the first or last one on the
list, otherwise you'd have to escape it or it would define a range (
e.g. :-, would mean "all characters in the range : to ,).
So, in order to keep consistency and not depend on character
positioning, you might want to escape all those characters that have a
special meaning in regular expressions (the following list is not
complete, so be aware of other characters like (, {, $ etc.):
String result = yourString.replaceAll("[\\-\\+\\.\\^:,]","");
If you want to get rid of all punctuation and symbols, try this regex:
\p{P}\p{S} (keep in mind that in Java strings you'd have to escape
back slashes: "\p{P}\p{S}").
A third way could be something like this, if you can exactly define
what should be left in your string:
String result = yourString.replaceAll("[^\\w\\s]","");
Here's less restrictive alternative to the "define allowed characters"
approach, as suggested by Ray:
String result = yourString.replaceAll("[^\\p{L}\\p{Z}]","");
The regex matches everything that is not a letter in any language and
not a separator (whitespace, linebreak etc.). Note that you can't use
[\P{L}\P{Z}] (upper case P means not having that property), since that
would mean "everything that is not a letter or not whitespace", which
almost matches everything, since letters are not whitespace and vice
versa.

the best way for character replacement in String in java

I want to check a string for each character I replace it with other characters or keep it in the string. and also because it's a long string the time to do this task is so important. what is the best way of these, or any better idea?
for all of them I append the result to an StringBuilder.
check all of the characters with a for and charAt commands.
use switch like the previous way.
use replaceAll twice.
and if one of the first to methods is better is there any way to check a character with a group of characters, like :
if (st.charAt(i)=='a'..'z') ....
Edit:
please tell the less consuming in time way and tell the reason.I know all of these ways you said!
If you want to replace a single character (or a single sequence), use replace(), as other answers have suggested.
If you want to replace several characters (e.g., 'a', 'b', and 'c') with a single substitute character or character sequence (e.g., "X"), you should use a regular expression replace:
String result = original.replaceAll("[abc]", "X");
If you want to replace several characters, each with a different replacement (e.g., 'a' with 'A', 'b' with 'B'), then looping through the string yourself and building the result in a StringBuilder will probably be the most efficient. This is because, as you point out in your question, you will be going through the string only once.
String sb = new StringBuilder();
String targets = "abc";
String replacements = "ABC";
for (int i = 0; i < result.length; ++i) {
char c = original.charAt(i);
int loc = targets.indexOf(c);
sb.append(loc >= 0 ? replacements.charAt(loc) : c);
}
String result = sb.toString();
Check the documentation and find some good methods:
char from = 'a';
char to = 'b';
str = str.replace(from, to);
String replaceSample = "This String replace Example shows
how to replace one char from String";
String newString = replaceSample.replace('r', 't');
Output: This Stting teplace Example shows how to teplace one chat ftom Stting
Also, you could use contains:
str1.toLowerCase().contains(str2.toLowerCase())
To check if the substring str2 exists in str1
Edit.
Just read that the String come from a file. You can use Regex for this. That would be the best method.
http://docs.oracle.com/javase/tutorial/essential/regex/literals.html
This is your comment:
I want to replace all of the uppercases to lower cases and replace all
of the characters except a-z with space.
You can do it like this:
str = str.toLowerCase().replaceAll("[^a-z]", " ");
Your requirement should be part of the question, not in comment #7 under a posted answer...
You should look into regex for Java. You can match an entire set of characters. Strings have several functions: replace, replaceAll, and match, which you may find useful here.
You can match the set of alphanumeric, for instance, using [a-zA-Z], which may be what you're looking for.

Difference between String replace() and replaceAll()

What's the difference between java.lang.String 's replace() and replaceAll() methods,
other than later uses regex? For simple substitutions like, replace . with / ,
is there any difference?
In java.lang.String, the replace method either takes a pair of char's or a pair of CharSequence's (of which String is a subclass, so it'll happily take a pair of String's). The replace method will replace all occurrences of a char or CharSequence. On the other hand, the first String arguments of replaceFirst and replaceAll are regular expressions (regex). Using the wrong function can lead to subtle bugs.
Q: What's the difference between the java.lang.String methods replace() and replaceAll(), other than that the latter uses regex.
A: Just the regex. They both replace all :)
http://docs.oracle.com/javase/8/docs/api/java/lang/String.html
PS:
There's also a replaceFirst() (which takes a regex)
Both replace() and replaceAll() replace all occurrences in the String.
Examples
I always find examples helpful to understand the differences.
replace()
Use replace() if you just want to replace some char with another char or some String with another String (actually CharSequence).
Example 1
Replace all occurrences of the character x with o.
String myString = "__x___x___x_x____xx_";
char oldChar = 'x';
char newChar = 'o';
String newString = myString.replace(oldChar, newChar);
// __o___o___o_o____oo_
Example 2
Replace all occurrences of the string fish with sheep.
String myString = "one fish, two fish, three fish";
String target = "fish";
String replacement = "sheep";
String newString = myString.replace(target, replacement);
// one sheep, two sheep, three sheep
replaceAll()
Use replaceAll() if you want to use a regular expression pattern.
Example 3
Replace any number with an x.
String myString = "__1_6____3__6_345____0";
String regex = "\\d";
String replacement = "x";
String newString = myString.replaceAll(regex, replacement);
// __x_x____x__x_xxx____x
Example 4
Remove all whitespace.
String myString = " Horse Cow\n\n \r Camel \t\t Sheep \n Goat ";
String regex = "\\s";
String replacement = "";
String newString = myString.replaceAll(regex, replacement);
// HorseCowCamelSheepGoat
See also
Documentation
replace(char oldChar, char newChar)
replace(CharSequence target, CharSequence replacement)
replaceAll(String regex, String replacement)
replaceFirst(String regex, String replacement)
Regular Expressions
Tutorial
List of patterns
The replace() method is overloaded to accept both a primitive char and a CharSequence as arguments.
Now as far as the performance is concerned, the replace() method is a bit faster than replaceAll() because the latter first compiles the regex pattern and then matches before finally replacing whereas the former simply matches for the provided argument and replaces.
Since we know the regex pattern matching is a bit more complex and consequently slower, then preferring replace() over replaceAll() is suggested whenever possible.
For example, for simple substitutions like you mentioned, it is better to use:
replace('.', '\\');
instead of:
replaceAll("\\.", "\\\\");
Note: the above conversion method arguments are system-dependent.
Both replace() and replaceAll() accepts two arguments and replaces all occurrences of the first substring(first argument) in a string with the second substring (second argument).
replace() accepts a pair of char or charsequence and replaceAll() accepts a pair of regex.
It is not true that replace() works faster than replaceAll() since both uses the same code in its implementation
Pattern.compile(regex).matcher(this).replaceAll(replacement);
Now the question is when to use replace and when to use replaceAll().
When you want to replace a substring with another substring regardless of its place of occurrence in the string use replace(). But if you have some particular preference or condition like replace only those substrings at the beginning or end of a string use replaceAll(). Here are some examples to prove my point:
String str = new String("==qwerty==").replaceAll("^==", "?"); \\str: "?qwerty=="
String str = new String("==qwerty==").replaceAll("==$", "?"); \\str: "==qwerty?"
String str = new String("===qwerty==").replaceAll("(=)+", "?"); \\str: "?qwerty?"
To throw more light with an example into how both are going to work for below code:
public static void main(String[] args)
{
String s = "My\\s aaab\\s is\\s aaab\\s name";
String s1 = s.replace("\\s", "c");
System.out.println(s1);
String s2 = s.replaceAll("\\s", "c");
System.out.println(s2);
}
Output:
Myc aaabc isc aaabc name
My\scaaab\scis\scaaab\scname
Explanation
s.replace replaces "\\s" sequence of characters with c. Hence, the output in first line.
s.replaceAll considers \\s as a regex rather(equivalent to space) and replaces spaces with c. \\s in String s is escaped with first \ encountered and becomes \s.
Intellij Idea is smart enough to notify you of the usage as well. If you take a closer look at below image, you will see the difference in interpretation by Intellij idea for replace and replaceAll usage.
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.
Old thread I know but I am sort of new to Java and discover one of it's strange things. I have used String.replaceAll() but get unpredictable results.
Something like this mess up the string:
sUrl = sUrl.replaceAll( "./", "//").replaceAll( "//", "/");
So I designed this function to get around the weird problem:
//String.replaceAll does not work OK, that's why this function is here
public String strReplace( String s1, String s2, String s )
{
if((( s == null ) || (s.length() == 0 )) || (( s1 == null ) || (s1.length() == 0 )))
{ return s; }
while( (s != null) && (s.indexOf( s1 ) >= 0) )
{ s = s.replace( s1, s2 ); }
return s;
}
Which make you able to do:
sUrl=this.strReplace("./", "//", sUrl );
sUrl=this.strReplace( "//", "/", sUrl );
As alluded to in wickeD's answer, with replaceAll the replacement string is handled differently between replace and replaceAll. I expected a[3] and a[4] to have the same value, but they are different.
public static void main(String[] args) {
String[] a = new String[5];
a[0] = "\\";
a[1] = "X";
a[2] = a[0] + a[1];
a[3] = a[1].replaceAll("X", a[0] + "X");
a[4] = a[1].replace("X", a[0] + "X");
for (String s : a) {
System.out.println(s + "\t" + s.length());
}
}
The output of this is:
\ 1
X 1
\X 2
X 1
\X 2
This is different from perl where the replacement does not require the extra level of escaping:
#!/bin/perl
$esc = "\\";
$s = "X";
$s =~ s/X/${esc}X/;
print "$s " . length($s) . "\n";
which prints
\X 2
This can be quite a nuisance, as when trying to use the value returned by java.sql.DatabaseMetaData.getSearchStringEscape() with replaceAll().
From Java 9 there is some optimizations in replace method.
In Java 8 it uses a regex.
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
From Java 9 and on.
And Stringlatin implementation.
Which perform way better.
https://medium.com/madhash/composite-pattern-in-a-nutshell-ad1bf78479cc?source=post_internal_links---------2------------------
replace() method doesn't uses regex pattern whereas replaceAll() method uses regex pattern. So replace() performs faster than replaceAll().
To add to the already selected "Best Answer" (and others that are just as good like Suragch's), String.replace() is constrained by replacing characters that are sequential (thus taking CharSequence). However, String.replaceAll() is not constrained by replacing sequential characters only. You could replace non-sequential characters as well as long as your regular expression is constructed in such a way.
Also (most importantly and painfully obvious), replace() can only replace literal values; whereas replaceAll can replace 'like' sequences (not necessarily identical).
replace works on char data type but replaceAll works on String datatype and both replace the all occurrences of first argument with second argument.

Categories