Replace all characters bigger than f - java

I use normally this command to replace characters in one String
myString.replace("f", "a").trim()
but this time I want to create a Hex String so I want to replace all characters that are bigger than f with the character a.
Is it possible to adapt this command ?

If you have an upper bounding character (I'll use z as an example), you could use a regular expression with replaceAll:
myString = myString.trim().replaceAll("[g-z]", "a");
The regular expression [g-z] means "any character g through z inclusive", see Pattern for details.
You may want to create the regular expression explicitly rather than relying on replaceAll's default version, if you want case-insensitivity for instance:
myString = Pattern.compile("[g-z]", Pattern.CASE_INSENSITIVE)
.matcher(myString.trim())
.replaceAll("a");

You can iterate the characters of your string, and replace those greater than f with what you want;
StringBuilder newString=new StringBuilder();
for (int i = 0; i < myString.length(); i++) {
char c = myString.charAt(i);
if (c > 'f') {
newString.append('a');
} else {
newString.append(c);
}
}

You could use a regular expression to do so [^a-f0-9] would select any characters not allowed in a string representing a hexadecimal number. You would need to replace all occurrences of this group by your desired value.

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"

Split a string with multiple delimiters while keeping these delimiters

Let's say we have a string:
String x = "a| b |c& d^ e|f";
What I want to obtain looks like this:
a
|
b
|
c
&
d
^
e
|
f
How can I achieve this by using x.split(regex)? Namely what is the regex?
I tried this link: How to split a string, but also keep the delimiters?
It gives a very good explanation on how to do it with one delimiter.
However, using and modifying that to fit multiple delimiters (lookahead and lookbehind mechanism) is not that obvious to someone who is not familiar with regex.
The regex for splitsplitting on optional spaces after a word boundary is
\\b\\s*
Note that \\b checks if the preceding character is a letter, or a digit or an underscore, and then matches any number of whitespace characters that the string will be split on.
Here is a sample Java code on IDEONE:
String str = "a| b |c& d^ e|f";
String regex = "\\b\\s*";
String[] spts = str.split(regex);
for(int i =0; i < spts.length && i < 20; i++)
{
System.out.println(spts[i]);
}

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.

Doing minus operation on string

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();

Categories