Replacing a character with other in java - java

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.

Related

String Replacement Error: id.replace(ch, "") not working

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.

Formatting String Array efficiently in Java

I was working on some string formatting, and I was curious if I was doing it the most efficient way.
Assume I have a String Array:
String ArrayOne[] = {"/test/" , "/this/is/test" , "/that/is/" "/random/words" }
I want the result Array to be
String resultArray[] = {"test", "this_is_test" , "that_is" , "random_words" }
It's quite messy and brute-force-like.
for(char c : ArrayOne[i].toCharArray()) {
if(c == '/'){
occurances[i]++;
}
}
First I count the number of "/" in each String like above and then using these counts, I find the indexOf("/") for each string and add "_" accordingly.
As you can see though, it gets very messy.
Is there a more efficient way to do this besides the brute-force way I'm doing?
Thanks!
You could use replaceAll and replace, as follows:
String resultArray[] = new String[ArrayOne.length];
for (int i = 0; i < ArrayOne.length; ++i) {
resultArray[i] = ArrayOne[i].replaceAll("^/|/$", "").replace('/', '_');
}
The replaceAll method searches the string for a match to the regex given in the first argument, and replaces each match with the text in the second argument.
Here, we use it first to remove leading and trailing slashes. We search for slashes at the start of the string (^/) or the end of the string (/$), and replace them with nothing.
Then, we replace all remaining slashes with underscores using replace.

Is there a way to remove characters from a string? Java

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!!!

Replace certain string in array of strings

let's say I have this string array in java
String[] test = {"hahaha lol", "jeng jeng jeng", "stack overflow"};
but now I want to replace all the whitespaces in the strings inside the array above to %20, to make it like this
String[] test = {"hahaha%20lol", "jeng%20jeng%20jeng", "stack%20overflow"};
How do I do it?
Iterate over the Array and replace each entry with its encoded version.
Like so, assuming that you are actually looking for URL-compatible Strings only:
for (int index =0; index < test.length; index++){
test[index] = URLEncoder.encode(test[index], "UTF-8");
}
To conform to current Java, you have to specify the encoding - however, it should always be UTF-8.
If you want a more generic version, do what everyone else suggests:
for (int index =0; index < test.length; index++){
test[index] = test[index].replace(" ", "%20");
}
Here's a simple solution:
for (int i=0; i < test.length; i++) {
test[i] = test[i].replaceAll(" ", "%20");
}
However, it looks like you're trying to escape these strings for use in a URL, in which case I suggest you look for a library which does it for you.
Try using String#relaceAll(regex,replacement); untested, but this should work:
for (int i=0; i<test.length; i++) {
test[i] = test[i].replaceAll(" ", "%20");
}
String[] test={"hahaha lol","jeng jeng jeng","stack overflow"};
for (int i=0;i<test.length;i++) {
test[i]=test[i].replaceAll(" ", "%20");
}
for each String you would do a replaceAll("\\s", "%20")
Straight out of the Java docs... String java docs
You can do String.replace('toreplace','replacement').
Iterate through each member of the array with a for loop.
You can use IntStream instead. Code might look something like this:
String[] test = {"hahaha lol", "jeng jeng jeng", "stack overflow"};
IntStream.range(0, test.length).forEach(i ->
// replace non-empty sequences
// of whitespace characters
test[i] = test[i].replaceAll("\\s+", "%20"));
System.out.println(Arrays.toString(test));
// [hahaha%20lol, jeng%20jeng%20jeng, stack%20overflow]
See also: How to replace a whole string with another in an array

Parsing comma delimited text in Java

If I have an ArrayList that has lines of data that could look like:
bob, jones, 123-333-1111
james, lee, 234-333-2222
How do I delete the extra whitespace and get the same data back? I thought you could maybe spit the string by "," and then use trim(), but I didn't know what the syntax of that would be or how to implement that, assuming that is an ok way to do it because I'd want to put each field in an array. So in this case have a [2][3] array, and then put it back in the ArrayList after removing the whitespace. But that seems like a funny way to do it, and not scaleable if my list changed, like having an email on the end. Any thoughts? Thanks.
Edit:
Dumber question, so I'm still not sure how I can process the data, because I can't do this right:
for (String s : myList) {
String st[] = s.split(",\\s*");
}
since st[] will lose scope after the foreach loop. And if I declare String st[] beforehand, I wouldn't know how big to create my array right? Thanks.
You could just scan through the entire string and build a new string, skipping any whitespace that occurs after a comma. This would be more efficient than splitting and rejoining. Something like this should work:
String str = /* your original string from the array */;
StringBuilder sb = new StringBuilder();
boolean skip = true;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (skip && Character.isWhitespace(ch))
continue;
sb.append(ch);
if (ch == ',')
skip = true;
else
skip = false;
}
String result = sb.toString();
If you use a regex for you split, you can specify, a comma followed by optional whitespace (which includes spaces and tabs just in case).
String[] fields = mystring.split(",\\s*");
Depending on whether you want to parse each line separately or not you may first want to create an array split on a line return
String[] lines = mystring.split("\\n");
Just split() on each line with the delimiter set as ',' to get an array of Strings with the extra whitespace, and then use the trim() method on the elements of the String array, perhaps as they are being used or in advance. Remember that the trim() method gives you back a new string object (a String object is immutable).
If I understood your problem, here is a solution:
ArrayList<String> tmp = new ArrayList<String>();
tmp.add("bob, jones, 123-333-1111");
tmp.add(" james, lee, 234-333-2222");
ArrayList<String> fixedStrings = new ArrayList<String>();
for (String i : tmp) {
System.out.println(i);
String[] data = i.split(",");
String result = "";
for (int j = 0; j < data.length - 1; ++j) {
result += data[j].trim() + ", ";
}
result += data[data.length - 1].trim();
fixedStrings.add(result);
}
System.out.println(fixedStrings.get(0));
System.out.println(fixedStrings.get(1));
I guess it could be fixed not to create a second ArrayLis. But it's scalable, so if you get lines in the future like: "bob, jones , bobjones#gmail.com , 123-333-1111 " it will still work.
I've had a lot of success using this library.
Could be a bit more elegant, but it works...
ArrayList<String> strings = new ArrayList<String>();
strings.add("bob, jones, 123-333-1111");
strings.add("james, lee, 234-333-2222");
for(int i = 0; i < strings.size(); i++) {
StringBuilder builder = new StringBuilder();
for(String str: strings.get(i).split(",\\s*")) {
builder.append(str).append(" ");
}
strings.set(i, builder.toString().trim());
}
System.out.println("strings = " + strings);
I would look into:
http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)
or
http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/java/util/Scanner.html
you can use Sting.split() method in java or u can use split() method from google guava library's Splitter class as shown below
static final Splitter MY_SPLITTER = Splitter.on(',')
.trimResults()
.omitEmptyStrings();

Categories

Resources