Get string from ("\n") new line operator - java

I have an arraylist that containing string like abc"\n"1234,cde"\n"567 fgh"\n"890. I want to get string from where it found new line. like from this array i want only 1234,567 and 890. here is what am doing. but it says "Incompatible Types"
Thanks actually i have show the dialog that containing these contacts.and than if user click on any contacts it opens the dialer activity.
for(String contact: manycontacts){
String contacts=contact.split("\\r?\\n");
}

split returns a String[] not a String
for(String contact: manycontacts){
String[] contacts=contact.split("\\r?\\n");
}
If you need it as one string you have to iterate over the array and concatinate the strings. or use commons-utils from apache to join it.

split method returns an array of strings String[]. In your code, you're returning a simply String. That is the incompatibility.
Simple change it to:
for(String contact: manycontacts){
String[] contacts=contact.split("\\r?\\n");
}

The split function returns an array of Strings, but you are trying to assign an array of strings to a single string, which throws this error. Rather use:
for(String contact: manycontacts){
String[] contacts=contact.split("\\r?\\n");
for(String split : contacts) {
//here you can go on and workt with a single splittet value
}
}

contact.split() is returning a String array, not a String, hence the type is incompatible. You'll need
String[] contacts = contact.split("\\r?\\n");

It is because split returns array of String which will be String[].

simply i used this.to trim the string.
String numberonly = contacts.substring(contact.indexOf('\n'));

Related

Restore List from a String in Java [duplicate]

In my software, since there is no Array data type in SQLite, I saved my ArrayList as a String. Now I need to use my array and want to convert it back to an ArrayList. How can I do it?
Here an example :
ArrayList<String> list = new ArrayList<String>();
list.add("name1");
list.add("name2");
list.add("name3");
list.add("name4");
list.add("name5");
list.add("name6");
String newList = list.toString();
System.out.println(newList);
Result: [name1, name2, name3, name4, name5, name6]
So now how can I convert this into an ArrayList<String>?
I believe this should work :
Arrays.asList(newList.substring(1, newList.length() - 1).replaceAll("\\s", "").split(","));
Take the string, remove the first and last bracket.
Remove each spaces.
Split by comma as delimiter, collect as list.
Note that if really you have to do this for a project, then there is something wrong in your code design. However, if this is just for curiosity purpose then this solution would work.
After testing
ArrayList<String> list = new ArrayList<String>();
list.add("name1");
list.add("name2");
list.add("name3");
list.add("name4");
list.add("name5");
list.add("name6");
String newList = list.toString();
List<String> myList = Arrays.asList(newList.substring(1, newList.length() - 1).replaceAll("\\s", "").split(","));
System.out.println(myList);
would compile properly and print :
[name1, name2, name3, name4, name5, name6]
Edit
As per your comments, if really you want your variable to be an ArrayList<String> instance then you could pass the list to ArrayList constructor :
ArrayList<String> myList = new ArrayList(Arrays.asList(newList.substring(1, newList.length() - 1).replaceAll("\\s", "").split(",")));
You can't cast directly as Arrays.asList use it own builtin java.util.Arrays$ArrayList class.
This is not possible to do without ambiguity. Consider:
ArrayList<String> list = new ArrayList<String>();
list.add("name1, name2");
list.add("name3, name4");
list.add("name5");
list.add("name6");
String newList = list.toString();
System.out.println(newList);
Result: [name1, name2, name3, name4, name5, name6]
In order to accurately recover the original elements in the general case, your string format must be smarter than ArrayList.toString(). Consider a pre-defined way of encoding lists of strings, perhaps a JSON array, which would result in something like this for my example:
["name1, name2", "name3, name4", "name5", "name6"]
JSON also defines how to handle strings with quotes via escaping and/or use of alternate string start/end characters ' and ":
["he said, 'hello'", 'she said, "goodbye"', 'I said, "it\'s raining"']
(I also agree with other commenters that your database design should be reconsidered, but wanted to provide a clear answer illustrating the issues with string encodings of lists.)
Then it the method that only accepts strings would be able to add a case where something like this were passed in?
methodThatOnlyAllowsStrings((Object)list);

Iterating over split string

After looking for a while, it's still bugging me:
I have a simple code where I want to retrieve data looking like:
data1/data2/style…
and I want to separate the data at each /. So I have written:
MyData = data.split("/")
and then:
for (i = 0; i < myData.size; i++)
to iterate over the values. But I'm getting the following error:
no signature of method length for type argument: () values: []
so I'm assuming that myData is empty.
if you want to iterate using an integer, you should use MyData.size() in the for loop.
But it is a better idea to do:
String[] myData = data.split("/");
for (String s: myData) {
System.out.println(s);
}
to use each string of the array.
If the iteration only iterates once over your array, then it may be your string that has a problem. As a double check, you may do:
System.out.println(myData.size());
You may also want to add a breakpoint after the .split() and look using a debugger if the array really contains all the strings you're expecting it to contain.
I am having some trouble understanding your question, even with the translation :)
In the line
mesDonnees = maDonnee.split("/");
mesDonnees needs to be a String array (String[]) and you can loop through it like:
for (String str : mesDonnees) {
//... do somwething with str
}
You can rename str something in French if you like, I couldn't think of a suitable name

Splitting by Tabs in Java

I have a file scanned line by line into an ArrayList.
I then create a new ArrayList in which I want to temporarily store that line into so that I may access certain values.
Ex. IDname(tab)IDnumber(tab)vote(tab)date
So, I create the temporary ArrayList named voteSubmission, and I go through every String in the fileRead array.
Why is it that I get the error incompatible type for my split method?
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
voteSubmission = x.split("\t");
}
The split method returns an array, not an ArrayList.
Either work with an array or convert it to an ArrayList manually.
x.split("\t"); this function will return an array not array list
The split function states that:
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.
Returns:
the array of strings computed by splitting this string around matches
of the given regular expression
You may try to change your code like this:
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
for(String value: x.split("\t"))
{
voteSubmission.add(value);
}
}
The output of split() is of type string[] array and you are trying to assign to an ArrayList type, which is incompatible.
Change your code to
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
String arr[] = x.split("\t");
if(arr != null && arr.length > 0)
{
for(String value: arr)
{
voteSubmission.add(value);
}
}
}
The error is: Type mismatch: cannot convert from String[] to ArrayList<String>
Which means that x.split("\t") provides a String[] array, but you assign it to an ArrayList.
If you'd like it to be an ArrayList, you'd have to convert it like this:
new ArrayList<String>(Arrays.asList(x.split("\t")));
But since you are doing this in a loop it is likely that you would like to store all Arrays within the ArrayList. To do this, you have to create an ArrayList of type String[], like this:
ArrayList<String[]> voteSubmission = new ArrayList<String[]>();
for(String x : fileRead){
voteSubmission.add((x.split("\t")));
}

How to get rid of duplicate entries in a comma separated string in java?

I have a string places="city,city,town". I need to get "city,town". Basically get rid of duplicate entries in the comma separated string.
places.split(","); will give me array of String. I wonder, if I can pass this array to a HashSet or something, which will automatically get rid of duplicates, but trying something like:
HashSet test=new HashSet(a.split(","));
gives the error:
cannot find symbol
symbol : constructor HashSet(java.lang.String[])
Any neat way of achieving this, preferably with least amount of code?
HashSet<String> test=new HashSet<String>(Arrays.asList(s.split(",")));
this is because HashSet does not have a constructor that expects an array. It expects a collection, which is what I am doing here by Arrays.asList(s.split(","))
String s[] = places.split(",");
HashSet<String> hs = new HashSet<String>();
for(String place:s)
hs.add(place);
If you care about the ordering I'd suggest you use a LinkedHashSet.
LinkedHashSet test = new LinkedHashSet(Arrays.asList(a.split(",")));
Another way of doing this in Java 8 would be:
Lets say you have a string str which is having some comma separated values in it. You can convert it into stream and remove duplicates and join back into comma separated values as given below:
String str = "1,2,4,5,3,7,5,3,3,8";
str = String.join(",",Arrays.asList(str.split(",")).stream().distinct().collect(Collectors.toList()));
This will give you a String str without any duplicate
String[] functions= commaSeperatedString.split(",");
List<String> uniqueFunctions = new ArrayList<>();
for (String function : functions) {
if ( !uniqueFunctions.contains(function.trim())) {
uniqueFunctions.add(function.trim());
}
}
return String.join(",",uniqueFunctions);
or you can use linkedHashset
LinkedHashSet result = new LinkedHashSet(Arrays.asList(functions.split(",")));

Referring a variable with a variable in java

I have got into a strange strange situation. I have 3 sets of strings like this
String set1q1="something"; //associated with randomNum=1
String set1q2="something";
String set1q3="something";
String set1q4="something";
... and so on
String set2q1="something"; //randomNum=2
String set2q2="something";
String set2q3="something";
String set2q4="something";
... and so on
String set3q1="something"; //randomNum=3
String set3q2="something";
String set3q3="something";
String set3q4="something";
... and so on
All these strings are initialised only once. Now in my program i generate a random number between 1-3. I converted this random number into a string and stored it into a string called set.
String set=randomNum.toString();
Now next intead of using "if-else" to send the data(if randomnum=1 send set1q1-5, if randomnum=2 then send set2q1-5), I want the appropriate data to be sent using one line.
For example: if random no 2 is chosen then set2q1 has to be sent where the "2" in between is has to be the value of "set"(which is defined above).
set"set"q1 //where set can be 1,2,3
Is there any way to do this?
What you are asking for is not possible;1 it's just not the way Java works. Why don't you just use an array, or a collection?
List<List<String>> allTheStrings = new ArrayList<List<String>>();
List<String> myStrings = null;
// Add a subset
myStrings = new ArrayList<String>();
myStrings.add("something");
myStrings.add("something");
myStrings.add("something");
allTheStrings.add(myStrings);
// Add another subset
myStrings = new ArrayList<String>();
myStrings.add("something");
myStrings.add("something");
myStrings.add("something");
allTheStrings.add(myStrings);
...
// Obtain one of the strings
String str = allTheStrings.get(1).get(2);
1. Except in the case where these variables are members of a class, in which case you could use reflection. But really, don't.
It is not possible. Local variable identifiers are converted to numbers (stack offsets) during compilation. But you should use arrays or collections anyway
Sounds like you want to index Strings by two indices. You should use a two-dimensional String array: String[][] strings. You may then access the desired string with strings[n][m]
Or you can achieve the same effect with a List<List<String>> strings if you need the dimensions of your 2D array to grow dynamically. You'd access the value you need with strings.get(n).get(m)
If you really want to access your strings by a composed name such as set2q1, then you just need a Map<String, String> strings. Then you'd access each value with strings.get("set" + m + "q" + n)
looks to me you should look into arrays, like this:
String[] strings = new String[]{"xxx", "yyy", "zzz"};
String string = strings[randomNumber];
create an arraylist instead and reference using the list index

Categories

Resources