Replace certain string in array of strings - java

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

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.

I'm trying to replace the colons and spaces with commas in Processing

I'm pretty new to Processing and Java so this is probably pretty simple. Just bear with me. It's just sliding over my head. This is the code I have
The txt file I'm pulling from consists of numbers like this:
1: 100
2: 200
3: 300 etc.
void setup() {
size(200,200);
String[] lines = loadStrings("WordFrequency.txt");
lines = lines.replaceAll(":", ",");
lines = lines.replaceAll(" ", ",");
}
}
Your code is trying to call replaceAll() on the array, which won't work. You have to iterate through the array and call it for every index. Also note that replaceAll() uses regular expressions, which is overkill for your purposes. I'd use replace() instead. More info can be found in the Java API.
So, what you're describing is three steps:
Step 1: Loop through every String in your array.
Step 2: Replace the colons with commas.
Step 3: Replace the spaces with commas.
Putting it all together, it looks like this:
for(int i = 0; i < lines.length; i++){
lines[i] = lines[i].replace(":", ",");
lines[i] = lines[i].replace(" ", ",");
}
You could shorten that to call replace() directly on the value returned from the first call to replace():
for(int i = 0; i < lines.length; i++){
lines[i] = lines[i].replace(":", ",").replace(" ", ",");
}
But this code isn't faster than the first option, so really you should stick with whatever code you understand the best.
Adding to Kevin's answer for replacing new line character. replace will not work because you have already parsed the new line characters while parsing the file into an array of strings.
You should append the strings after replace. Something like this:
String fileString = "";
for(int i = 0; i < lines.length; i++){
lines[i] = lines[i].replace(":", ",");
lines[i] = lines[i].replace(" ", ",");
fileString += lines[i];
}

String replace function not working in android

I used the following code to replace occurrence of '\' but its not working.
msg="\uD83D\uDE0A";
msg=msg.replace("\\", "|");
I spent a lot of time in Google. But didn't find any solution.
Also tried
msg="\uD83D\uDE0A";
msg=msg.replace("\", "|");
The msg string defined must also use an escape character like this:
msg="\\uD83D\\uDE0A";
msg=msg.replace("\\", "|");
That code will work and it will result in: |uD83D|uDE0A
If you want to show the unicode integer value of a unicode character, you can do something like this:
String.format("\\u%04X", ch);
(or use "|" instead of "\\" if you prefer).
You could go through each character in the string and convert it to a literal string like "|u####" if that is what you want.
From what I understand, you want to get the unicode representation of a string. For that you can use the answer from here.
private static String escapeNonAscii(String str) {
StringBuilder retStr = new StringBuilder();
for(int i=0; i<str.length(); i++) {
int cp = Character.codePointAt(str, i);
int charCount = Character.charCount(cp);
if (charCount > 1) {
i += charCount - 1; // 2.
if (i >= str.length()) {
throw new IllegalArgumentException("truncated unexpectedly");
}
}
if (cp < 128) {
retStr.appendCodePoint(cp);
} else {
retStr.append(String.format("\\u%x", cp));
}
}
return retStr.toString();
}
This will give you the unicode value as a String which you can then replace as you like.

Replacing a character with other in 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.

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