Parsing specific words out of a string [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
For a Java program I need to write, I am supplied with a string that can contain any number of the following words in any order: char, double, int
So it could look like any of these:
"charintdouble"
"charchar"
"intdoublechardouble"
I then want to store each word in an array in the order they appear in the string. So an input string of "intdoublechardouble" would result in an array that looks like this:
{"int", "double", "char", "double"}
What would be the best way of parsing the string to get all of the words out of it?

You can use replace and split methods of string
String str="intdoublechardouble";
str=str.replace("char", "char-").replace("double", "double-").replace("int", "int-");
String[] tokens=str.split("-");
Now tokens contain [int, double, char, double]

I'd start with thinking about how you might do this in real life and try turning that into a Java algorithm. A somewhat inefficient way would be to string.split on the string for each element in a string array {"char", "int", "double"}, and put all the tokens created by string.split in the correct order.

If you need an effective solution for this particular problem, this should do the trick
public Object extractWords(String s) {
ArrayList<String> array = new ArrayList<String>();
s = s.replace("t", "t,");
s = s.replace("r", "r,");
s = s.replace("e", "e,");
StringTokenizer tokenizer = new StringTokenizer(s, ",");
while (tokenizer.hasMoreTokens()) {
array.add(tokenizer.nextToken());
}
return array;
}
Obviously, this won't work in general. For other cases I guess you would have to traverse the input string char by char and compare it to the list of target words, as you have suggested.

Related

java: string split loose last element [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
im sorry for the screen shot
the strange result for me,
while result of split does not contain the last element,
from my pov the correct result must be
['[','xtrue','']
am i right?
public static List<String> splitString(String source, String delimiter) {
if (Objects.equals(delimiter, "[")) {
return Arrays.asList(source.split("\\["));
}
String[] sArr = source.split(delimiter);
return Arrays.asList(sArr);
}
sure, guess im not safe with split operator, but a little search on google do not solve my question how to use for get as i want
A per documentation:
Trailing empty strings are therefore not included in the resulting array.
So the output is correct.
If you want trailing empty strings you'll have to use the two-parameters version of split passing a negative integer as the second parameter, since
If the limit is negative then the pattern will be applied as many times as possible and the [resulting] array can have any length
So, like you say in your own answer
source.split(delimiter, -1);
will include the empty string after the last " .
for the community
the solution for my case
source.split(delimiter, -1);
thx

How to cast an integer array to a String array without creating separate array of strings and adding individually casted int array items to it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
int[] locations = {ran1,ran2,ran3};
String positions = locations.toString();
When cast this way, it casts the int[] into a String but not to String[]. I tried casting individual integers ran1, ran2, ran3 into String primitives and then adding them to the different String[] to use in the code, but why an array got cast into only the primitive String but not into an array. Am I using the wrong syntax to cast an entire int[] to String[]? Is there any other method to cast an entire array?
You cannot "cast" a int[] to a String[] (neither can you "cast" an int to a String): what you can and have to do is "convert".
To convert from int to String you can use Integer#toString() method.
To convert an array, there's no built-in method but you can do as suggested in a comment:
IntStream.of(locations).mapToObj(Integer::toString).toArray(String[]::new)
int arr[]= {1,2,3,4,5,6};
String x= Arrays.toString(arr);

create an array from elements in a string, elemets start with certain key/sign [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to abstract an array with text strings that reside in a text, each text element starts with a certain sign or key e.g. $ or &. how can I achieve this?
so "$Huey, $Dewey, and $Louie all live in Duckcity. $Goofy and $Mickey live there too." should result in
string characters = {"Heuy","Dewey", "Louie", "Goofy","Mickey"};
Use Streams and a filter.
String s = "$Huey, $Dewey, and $Louie all live in Duckcity. $Goofy and $Mickey live there too.";
String[] a =
// Split it into words.
Arrays.stream(s.split("[, .]"))
// Pick only the words starting with '$'
.filter(w -> w.startsWith("$"))
// Remove the '$'
.map(w -> w.substring(1))
// Make a list.
.collect(Collectors.toList())
// And turn it into an array.
.toArray(new String[0]);
System.out.println(Arrays.toString(a));
Prints:
[Huey, Dewey, Louie, Goofy, Mickey]
Go through the elements and check whether or not the string starts with the sign/key. If it does, add it to a String[]

How search a datum in ArrayList<StringBuilder> with indexOf [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How search a datum in ArrayList with indexOf
ArrayList<StringBuilder> state = new ArrayList<StringBuilder>();
state.add(new StringBuilder("A"));
state.add(new StringBuilder("B"));
state.add(new StringBuilder("C"));
state.add(new StringBuilder("D"));
System.out.println(state.indexOf(new StringBuilder("B"))); //Out: -1
You are using an ArrayList of StringBuilderobjects.
As StringBuilder is used for building strings, and not as actually Strings , you can't use indexOf(s), as the whole object itself should be equal to the one you are comparing so that it returns true.
In order to solve this problem, you should build the String however you want with the StringBuilder, and make an ArrayList of already-built Strings only, like this:
ArrayList<String> state = new ArrayList<String>();
StringBuilder a = new StringBuilder("A")
//Do whatever you want to a
state.add(a.toString());
state.add(b.toString());
state.add(c.toString());
state.add(d.toString());
.....
System.out.println(state.indexOf("B")); //Out: 1
This is because it searches by reference and you want to search by the contents of the string builder.
boolean there = state.stream() // use streams API
.anyMatch(sb -> sb.toString().equals("B")); // check string equals
System.out.println(there); // print if it's there

Put only numeric strings into hashmap [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to build a hashMap from an ArrayList which contains all the variables I need plus their respective values.
The problem is, my arrayList contains variables with non numeric values (eg: var1 = "*$&/#"). How could I filter the data contained in the arrayList to get only the numeric strings.
I tried using regular expressions but the data get filtered too much and some of the variables I need get lost. I guess i'm not using the legit regex. So I tried matching the following regex and if not, assign "0" to my variable. Here's roughly what I've tried thus far:
private static final String REGEX = "-?\\d+(\\.\\d+)?";
//...
if (val_ens1_sol.matches(REGEX) && val_ens1_bord.matches(REGEX)) {
reslutatsMap.put(key_ens1_sol, val_ens1_sol);
reslutatsMap.put(key_ens1_bord, val_ens1_bord);
} else {
val_ens1_sol = "0";
val_ens1_sol = "0";
}
This was already answered somewhere else (How to check if a String is numeric in Java) but to discuss the possibilities: Either you assume that you have numeric strings, parse the string is integer or double and catch the number format exception, or you use a regex.
You can do this using BigDecimal, which will parse all integers/decimal point floats/scientific floats:
try {
new BigDecimal(val_ens1_sol);
new BigDecimal(val_ens1_bord);
} catch (NumberFormatException ignored) {
// deal with at least one value not being a number
}

Categories

Resources