I'm trying to add a string to an ArrayList<String> using .add(string). This works, but it separates the variables using a comma (","). This makes it problematic for me later on when I try to split the string, because some of the sentences contain commas.
How do I change the comma to another variable when adding a string to an ArrayList?
What you are doing is using the toString method of the ArrayList which will print each of the element of that ArrayList separated with commas.
solution:
just iterate to all of the Arraylist and append them using the String Builder.
sample:
ArrayList<String> s= new ArrayList<>();
s.add("adsasd");
s.add("adsasd");
s.add("adsasd");
s.add("adsasd");
StringBuilder s2 = new StringBuilder();
for(String s3 : s)
s2.append(s3+" ");
System.out.println(s2);
result:
adsasd adsasd adsasd adsasd
let ArrayList str contain the list.
String myString = str.toString();
myString.replaceAll(",","something");
Also you can use String Builder.
You have a ArrayList. I suppose you are doing something with the particular index of the arrayList. So, get that index and then get the String and split it using substring by getting the index of ",". But it this method is not that convenient as your code will be long.
Related
I have One String
which has value
String someString = "/category/subcategory/Fruit/apple/";
I want to separate "Fruit" from string.
Make an Array of Strings by splitting with / character like:
String[] split = someString.split("/");
This Array split[] has all the elements separated. You can use whichever you want.
String[] values = someString.split("/");
Log.i(TAG, values[3]);
ie. My string is "pqrstuw". How can I get " t" with its postion 4. I want to edit each character and change its postion. Is it possible in Java?
You can use a for loop and call String#charAt()... this is the character at the zero base-index, always having in mind that Strings objects are inmutable.
Assuming a string variable 'word' contains what you need. Use the code below to print the various characters in it. Also add the headerfile needed ( java.lang.String; )
int size = word.length(); // Get length of string
for(int i =0 ; i<size ; i++) {
System.out.println(word.charAt(i)); // To print i+1'th letter
}
string_name.charAt(i) will give you the 'i+1'th character in your string. In your case, if word = "pqrstuvw", then word.charAt(3) will give you 't' which is the 4th character of the string.As for your second question, you need to be a little more clear on what kind of position changing you want to do in your question.
The following is an answer from another similar question: "Replacing a character at a specific position in the string.
Strings are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
All we know that String is a Immutable (final) class defined in JDK. So, It is not recommend and very cozy to manipulate a String in Java.
There are two simple ways to manipulate the string in Java.
Using StringBuilder Class.
Change to char Array Using .charArray() method of String Class .
Using StringBuilder Class
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type.
Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder.
The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
Now Here is the code
String str = "pqrstuw";
StringBuilder strBuild = new StringBuilder(str);
strBuild.indexOf("t"); //return first index where t is found which is 4.
strBuild.lastIndexOf("t"); //return last index where t is found which is 4.
strBuild.getCharAt(4); // you will get t.
strBuild.setCharAt(4,'v');
strBuild.append("v"); append element at last.
there are various more overloaded method there is StringBuilder Class. You can do it in Your Way of Manipulation.
Using char Array
String str = "pqrstuw";
char [] arr_str = str.toCharArray(); //it convert your String into a char Array.
//after manipulation you can change your char Array to String as like
str = arr_str.toString();
I have the following String
[http://images.com/1.jpg, http://images.com/2.jpg, http://images.com/3.jpg]
I want to store the contents of this array inside a string array or array list of type string.
I tried using .split method, but it fails mainly because the string also contains the brackets at the beginning.
String[] splittedString = theString.substring(1, theString.length()-1).split(", ")
Notice space after comma in the split method.
Use substring to exclude the string from the brackets:
mystring = mystring.substring(1,mystring.length()-1);
And then the split:
String[] myarray = mystring.split(", ");
String arry[] = yourstr.replace("[", "").replace("]", "").split(",");
Escape the first and the last characters of your String containing the brackets before using the split() method, like this :
yourString= yourString.substring(1, yourString.length()-1));
// do your split() method
Optionally you can use StringTokenizer.
I am having a difficult time figuring out how to split a string like the one following:
String str = "hi=bye,hello,goodbye,pickle,noodle
This string was read from a text file and I need to split the string into each element between the commas. So I would need to split each element into their own string no matter what the text file reads. Keep in mind, each element could be any length and there could be any amount of elements which 'hi' is equal to. Any ideas? Thanks!
use split!
String[] set=str.split(",");
then access each string as you need from set[...] (so lets say you want the 3rd string, you would say: set[2]).
As a test, you can print them all out:
for(int i=0; i<set.length;i++){
System.out.println(set[i]);
}
If you need a bit more advanced approach, I suggest guava's Splitter class:
Iterable<String> split = Splitter.on(',')
.omitEmptyStrings()
.trimResults()
.split(" bye,hello,goodbye,, , pickle, noodle ");
This will get rid of leading or trailing whitespaces and omit blank matches. The class has some more cool stuff in it like splitting your String into key/value pairs.
str = str.subString(indexOf('=')+1); // remove "hi=" part
String[] set=str.split(",");
I'm wondering: Do you mean to split it as such:
"hi=bye"
"hi=hello"
"hi=goodbye"
"hi=pickle"
"hi=noodle"
Because a simple split(",") will not do this. What's the purpose of having "hi=" in your given string?
Probably, if you mean to chop hi= from the front of the string, do this instead:
String input = "hi=bye,hello,goodbye,pickle,noodle";
String hi[] = input.split(",");
hi[0] = (hi[0].split("="))[1];
for (String item : hi) {
System.out.println(item);
}
I have added several characters in a list to replace in a string. Here they are:
List<Character> list = new ArrayList<Character>();
list.add(',');
list.add('?');
list.add(',');
list.add(':');
list.add('-');
list.add('(');
list.add(')');
list.add(';');
list.add('/');
I want to replace all occurrences of the character in the list in a string "s".
s.replaceAll(list, "");
I can't do that, of course, because list is NOT a string. But what can I do instead?
EDIT so if
String s = "I am cool; not good!";
I want the list to recognize that it contains ";" and "!", and replace those characters in the String s with nothing. So the result would be:
"I am cool not good"
Rather than use a List<Character>, I would use a regex:
s.replaceAll("[,?:();/-]","");
If you absolutely must define your characters in a List, convert the List to such a regex first.
Rather than List why not use a regular expression. Otherwise you may be stuck with something like:
StringBuilder mySB = new StringBuilder(myString);
for (Character myChar : list) {
mySB.replace(String.valueOf(myChar), "");
}
myString = mySB.toString();
check out Apache Commons StringUtils.replaceEach((String text,
String[] searchList,
String[] replacementList)) it will allow you to provide a list of values to search for and a list of associated replacements in a single line.
Note: This will throw IndexOutOfBoundsException if the lengths of the search and replacement arrays are not the same