I am trying to replace characters in a string
for (String word : stringArray){
int k = 33;
char d ="";
while (k < 64){
char c = k;
word = word.replace(c, ""); // THIS LINE GIVES AN ERROR
k++;
}
}
I am trying to get rid of all the non-letter characters between ASCII id 32 (!) and ASCII id 64 (#), inclusive. I am using stringid.replace(char, char) as suggested here.
However, "" in the second argument of replace is being treated as a string in Eclipse, which is giving an error as "type mismatch" (since replace expects arguments which are both characters).
I have tried '' instead of "" but that doesn't seem to fix the problem. What should I do? Thanks in advance.
EDIT: changed word.replace(c, ""); to word = word.replace(c,""); . Thanks to commenter for pointing this out. However, the problem still occurs.
You have to change quite a bit of your code for this to work:
for (int i = 0; i < stringArray.length; i++) {
int k = 33;
while (k < 64){
stringArray[i] = stringArray[i].replace("" + k, "");
k++;
}
}
The key points are:
Strings are immutable, so if you modify them, you have to reassign them
If you modify an iteration variable in a for loop, the original value in the array won't be changed, you also have to reassign it inside the array
There's no "empty char", so the replacement must be between strings
Why don't you put all the characters that you want to replace in a separate string and use regex to replace them all from your string?
String charsToBeReplaced = "[!\"#$%&'()*+,-.\\/0123456789:;<=>?#]"; //your ASCII 33 to 64 characters... notice that forward slash and double quotes is escaped here
for (int i=0; i<stringArray.length; i++){
stringArray[i] = stringArray[i].replaceAll(charsToBeReplaced, "");
}
DEMO
Just to present another answer using regular expressions:
Pattern p = Pattern.compile("[\\x21-\\x40]");
for (int i=0; i<stringArray.length; i++){
stringArray[i] = p.matcher(stringArray[i]).replaceAll("");
}
This is probably more efficient that Raman Sahasi's answer as we only have to compile the pattern once.
Related
I'm facing a problem in replacing character in a string with its index.
e.g I wanna replace every '?' With its index String:
"a?ghmars?bh?" -> will be "a1ghmars8bh11".
Any help is truly appreciated.
P.s I need to solve this assignment today so I can pass it to my instructor.
Thanks in adv.
So far I get to manage replacing the ? With 0; through this piece of code:
public static void main(String[] args) {
String name = "?tsds?dsds?";
String myarray[] = name.split("");
for (int i = 0; i < myarray.length; i++) {
name = name.replace("?", String.valueOf(i++));
}
System.out.println(name);
output:
0tsds0dsds0
it should be:
0tsds5dsds10
For simple replace operations, String.replaceAll is sufficient. For more complex operations, you have to retrace partly, what this method does.
The documentation of String.replaceAll says that it is equivalent to
Pattern.compile(regex).matcher(str).replaceAll(repl)
whereas the linked documentation of replaceAll contains a reference to the method appendReplacement which is provided by Java’s regex package publicly for exactly the purpose of supporting customized replace operations. It’s documentation also gives a code example of the ordinary replaceAll operation:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
Using this template, we can implement the desired operation as follows:
String name = "?tsds?dsds?";
Matcher m=Pattern.compile("?", Pattern.LITERAL).matcher(name);
StringBuffer sb=new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, String.valueOf(m.start()));
}
m.appendTail(sb);
name=sb.toString();
System.out.println(name);
The differences are that we use a LITERAL pattern to inhibit the special meaning of ? in regular expressions (that’s easier to read than using "\\?" as pattern). Further, we specify a String representation of the found match’s location as the replacement (which is what your question was all about). That’s it.
In previous answer wrong read question, sorry. This code replace every "?" with its index
String string = "a?ghmars?bh?das?";
while ( string.contains( "?" ) )
{
Integer index = string.indexOf( "?" );
string = string.replaceFirst( "\\?", index.toString() );
System.out.println( string );
}
So from "a?ghmars?bh?das?" we got "a1ghmars8bh11das16"
You are (more or less) replacing each target with the cardinal number of the occurrence (1 for 1st, 2 for 2nd, etc) but you want the index.
Use a StringBuilder - you only need a few lines:
StringBuilder sb = new StringBuilder(name);
for (int i = name.length - 1; i <= 0; i--)
if (name.charAt(i) == '?')
sb.replace(i, i + 1, i + "");
Note counting down, not up, allowing for the replacement index to be multiple digits, which if you counted up would change the index of subsequent calls (eg everything would get shuffled to the right by one char when the index of "?" was 10 or more).
I think this may work i have not checked it.
public class Stack{
public static void main(String[] args) {
String name = "?tsds?dsds?";
int newvalue=50;
int countspecialcharacter=0;
for(int i=0;i<name.length();i++)
{
char a=name.charAt(i);
switch(a)
{
case'?':
countspecialcharacter++;
if(countspecialcharacter>1)
{
newvalue=newvalue+50;
System.out.print(newvalue);
}
else
{
System.out.print(i);
}
break;
default:
System.out.print(a);
break;
}
}
}
}
Check below code
String string = "a?ghmars?bh?das?";
for (int i = 0; i < string.length(); i++) {
Character r=string.charAt(i);
if(r.toString().equals("?"))
System.out.print(i);
else
System.out.print(r);
}
I've been searching for hours but can't find an answer, I apologize if this has been answered before.
I'm trying to check each word in a message for any double letters and remove the extra letter, words like wall or doll for example would become wal or dol. the purpose is for a fake language translation for a game, so far I've gottan as far as identifying the double letters but don't know how to replace them.
here's my code so far:
public String[] removeDouble(String[] words){
Pattern pattern = Pattern.compile("(\\w)\\1+");
for (int i = 0; i < words.length; i++){
Matcher matcher = pattern.matcher(words[i]);
if (matcher.find()){
words[i].replaceAll("what to replace with?");
}
}
return words;
}
You can do the whole replacement operation in one statement if you use back references:
for (int i = 0; i < words.length; i++)
words[i] = words[i].replaceAll("(.)\\1", "$1");
Note that you must assign the value returned from string methods that (appear to) change strings, because they return new strings rather than mutate the string.
String.replaceAll does not modify the string in-place. (Java String is immutable) You need assign the returned value back.
And the String.replaceAll accepts two parameters.
Replace following line:
words[i].replaceAll("what to replace with?");
with:
words[i] = "what to replace with?";
I am having trouble removing letters from a string. String ALPHABET = "abcdefghjklmnopqrstuvwxyz"; User puts in a string. "klmn". How would i remove klmn from the alphabet? Is there a way? Other then putting it into an array?
This is what i started with. This only removes the last letter in the string. Whats my problem here.
for(int i = 0; i < message.length(); i++){
for(int j = 0; j < ALPHABET.length(); j++){
letter = message.charAt(i);
if(ALPHABET.charAt(j) == message.charAt(i)){
newALPHABET = ALPHABET.replace(letter, ' ');
}
}
}
Don't know what you want to do but you can use String#replace
String alphabet = "abcdefghjklmnopqrstuvwxyz";
alphabet = alphabet.replace("klmn","");
Write a method to delete it.. the logic here is replace the char you want to delete with the next char.. and in place of second one keep the third char and so on..
if you want to delete a large length of String..
then use the method Replace..
You can do that with regular expressions. Try the next:
static String ALPHABET = "abcdefghjklmnopqrstuvwxyz";
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Letters: ");
Pattern p = Pattern.compile("[" + Pattern.quote(input) +"]");
Matcher m = p.matcher(ALPHABET);
String result = m.replaceAll("");
System.out.println(result);
}
If you simply wanted to replace a character or simple substring, then String.replace is the solution.
If you wanted to replace matches a regex, then String.replaceAll is the the solution.
The reason your code is not working is because there are a couple of bugs in it:
You appear to be under the impression that String.replace(char, char) replaces a single character instance. In fact, it replaces all instance of the first character in the String.
Each loop iteration creates a new String and assigns it to newALPHABET. But then you start again with ALPHABET on the next iteration.
If the aim is to produce an "alphabet" that excludes the letters in message, then the correct solution is something like this:
for (int i = 0; i < message.length(); i++) {
ALPHABET = ALPHABET.replace(message.charAt(i), ' ');
}
... except that you should NOT use ALPHABET as the name of a variable. It should be alphabet!!!
Dear stackoverflow members,
I have a small problem,
I want to replace some characters in my string with other in java, and my code to do it is as follow,
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1.removeAllItems();
String str = new GenericResource_JerseyClient().getlist();
String [] temp = null;
temp = str.split(",");
temp[1]=temp[1].replaceAll("'", "");
temp[1]=temp[1].replaceAll(" ", "");
temp[1]=temp[1].replace("[", "");
temp[1]=temp[1].replace("]", "");
for(int i =0; i < temp.length ; i++)
{
jComboBox1.addItem(temp[i]);
} // TODO add your handling code here: // TODO add your handling code here:
// TODO add your handling code here
}
As it can be seen from the above code i replace "'","[","]",and empty space with nothing.
As it can be also seen from the code that i split the string into two. In the part of string after , the code works well but the part of string before , the code doesn't seem to work properly.
i have also attached a copy of the dropdown list output in the client side.
Any help would be very much appreciated on how to remove [ and ' from the string.
Cheers.
Perform all your replacements BEFORE splitting the string. This is better than executing the same code in a loop.
For example:
String cleanString = str.replace("'", "").replace(" ", "").replace("[", "").replace("]", "");
String[] temp = cleanString.split(",");
for(int i = 0; i < temp.length ; i++) {
jComboBox1.addItem(temp[i]);
}
You're only performing replacements on temp[1] - whereas the problem appears to be in the first item shown in the dropdown, which is presumably the data from temp[0].
I suspect you should just extract the removal code into a separate method, and call it in your loop:
for(int i =0; i < temp.length ; i++)
{
jComboBox1.addItem(removeUnwantedCharacters(temp[i]));
}
Additionally, I would strongly recommend that you use replace rather than replaceAll for any case where you don't explicitly want regular expression pattern matching. It can be very confusing to have code such as:
foo = foo.replaceAll(".", "");
which looks like it's removing dots, but will actually remove all characters, as the "." is treated as a regular expression...
well, you performing replace only in item with index 1 (the second one). But then adding to the combo all of them (two, actually). Try:
for(int i =0; i < temp.length ; i++){
temp[i]=temp[i].replaceAll("'", "");
temp[i]=temp[i].replaceAll(" ", "");
temp[i]=temp[i].replace("[", "");
temp[i]=temp[i].replace("]", "");
}
You are only doing the replacing on the temp[1] which is the second part of the string. You need to do in temp[0] as well. It is better to create a function that takes a string and does the replacements and call it on both temp[0] and temp[1]. You can also look at using a regular expression to replace all characters at once instead of doing it one at a time.
String [] temp = String.split(",")
for (int i = 0;i<temp.length;i++) {
temp[i] = replaceSpecialChars(temp[i]);
}
public String replaceSpecialChars(String input) {
// add your replacement logic here
return input
}
Common problem.
I think this code meets your requirements.
How can I get the int value from a string such as 423e - i.e. a string that contains a number but also maybe a letter?
Integer.parseInt() fails since the string must be entirely a number.
Replace all non-digit with blank: the remaining string contains only digits.
Integer.parseInt(s.replaceAll("[\\D]", ""))
This will also remove non-digits inbetween digits, so "x1x1x" becomes 11.
If you need to confirm that the string consists of a sequence of digits (at least one) possibly followed a letter, then use this:
s.matches("[\\d]+[A-Za-z]?")
The NumberFormat class will only parse the string until it reaches a non-parseable character:
((Number)NumberFormat.getInstance().parse("123e")).intValue()
will hence return 123.
Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?
Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.
If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.
You can also use Scanner :
Scanner s = new Scanner(MyString);
s.nextInt();
Just go through the string, building up an int as usual, but ignore non-number characters:
int res = 0;
for (int i=0; i < str.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') continue;
res = res * 10 + (c - '0');
}
Perhaps get the size of the string and loop through each character and call isDigit() on each character. If it is a digit, then add it to a string that only collects the numbers before calling Integer.parseInt().
Something like:
String something = "423e";
int length = something.length();
String result = "";
for (int i = 0; i < length; i++) {
Character character = something.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
System.out.println("result is: " + result);