Is there a method you can use to change the format of an array (as in the way it is separated by commas and enclosed in brackets when it's printed out). I want to get rid of the brackets and commas so that the terms are only separated by spaces.
Then don't use the Arrays.toString() method, write your own:
StringBuilder sb = new StringBuilder();
for (xxxx val : array) {
sb.append(val).append(" ");
}
sb.setLength(sb.length() - 1);
return sb.toString();
Yes, use Guava's Joiner class for full control of your output.
E.g.,
Integer[] foo = new Integer[] {1, 2, 3};
System.out.println(Joiner.on(' ').join(foo);
gives 1 2 3
You can replace the , and the ( and )
String formatedString = myArrayList.toString()
.replace(",", " ") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "");
Use org.apache.commons.lang.StringUtils.
E.g.:
String[] array = {"A","B"};
System.out.println( StringUtils.join(array, "_") );
Related
I am giving string input as "He is a very very good boy, isn't he?"
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
String[] split = s.split("[',',''','?','\\s','(',')',',',';']");
for(String s1:split){
if(s1.equalsIgnoreCase(""))
{
s1.trim();
}
System.out.println(s1);
}
Expected Result:
Actual Result:
Just put a + after your bracket for:
String[] split = s.split("[',',''','?','\\s','(',')',',',';']+");
Or simplify it to:
String[] split = s.split("[,'?\\s();]+");.
It will work how you expected since it will now match multiple characters in a row.
You will also no longer need to use trim() and just call:
for(String s1:split){
System.out.println(s1);
}
.trim() removes whitespace. I.e. " " becomes "". It is not able, however, to remove it from the list. String.split() doesn't know about your list.
The following will do what you want:
String[] split = s.split("<your regex>");
List<String> list = Arrays.asList(split);
list.stream() // convert to a stream for easy filtering
.filter(s -> s.trim().equals("")) // if s.trim().equals(""), remove it from the list/stream
.forEach(System.out::println); // print every remaining element
This question already has answers here:
split string only on first instance - java
(6 answers)
Closed 4 years ago.
If a client wants to store a message into a txt file, user uses keyword msgstore followed by a quote.
Example:
msgstore "ABC is as easy as 123"
I'm trying to split msgstore and the quote as two separate elements in an array.
What I currently have is:
String [] splitAdd = userInput.split(" ", 7);
but the problem I face is that it splits again after the second space so that it's:
splitAdd[0] = msgstore
splitAdd[1] = "ABC
splitAdd[2] = is
My question is, how do I combine the second half into a single array with an unknown length of elements so that it's:
splitAdd[0] = msgstore
splitAdd[1] = "ABC is as easy as 123"
I'm new to java, but I know it's easy to do in python with something like (7::).
Any advice?
Why do you have limit parameter as 7 when you want just 2 elements? Try changing it to 2:-
String splitAdd[] = s.split(" ", 2);
OR
String splitAdd[] = new String[]{"msgstore", s.split("^msgstore ")[1]};
substring on the first indexOf "
String str = "msgstore \"ABC is as easy as 123\"";
int ind = str.indexOf(" \"");
System.out.println(str.substring(0, ind));
System.out.println(str.substring(ind));
edit
If these values need to be in an array, then
String[] arr = { str.substring(0, ind), str.substring(ind)};
You can use RegExp: Demo
Pattern pattern = Pattern.compile("(?<quote>[^\"]*)\"(?<message>[^\"]+)\"");
Matcher matcher = pattern.matcher("msgstore \"ABC is as easy as 123\"");
if(matcher.matches()) {
String quote = matcher.group("quote").trim();
String message = matcher.group("message").trim();
String[] arr = {quote, message};
System.out.println(Arrays.toString(arr));
}
This is more readable than substring a string, but it definetely slower. As alternative, you can use substirng a string:
String str = "msgstore \"ABC is as easy as 123\"";
int pos = str.indexOf('\"');
String quote = str.substring(0, pos).trim();
String message = str.substring(pos + 1, str.lastIndexOf('\"')).trim();
String[] arr = { quote, message };
System.out.println(Arrays.toString(arr));
Excuse the brevity, currently on mobile.
I have a string array of values ABC, DEF, GHI that I would like to change to capitalized form: Abc, Def, Ghi
My code looks something like this:
import org.apache.commons.lang3.text.WordUtils;
....
final String[] split = stringToConvert.split(", ");
final StringBuilder sb = new StringBuilder();
for ( String s : split) {
//s = WordUtils.capitalizeFully(s.toLowerCase());
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(WordUtils.capitalizeFully(s.toLowerCase()));
}
return sb.toString();
The first value is always abc, but the second and following ones are correct, e.g. Def, Ghi. I don't know why the first value stays lowercase.
Any help would be appreciated!
Check your code again.
StringBuilder buf = new StringBuilder();
for (String str : new String[]{"ABC", "DEF", "GHI"})
buf.append(WordUtils.capitalizeFully(str.toLowerCase()));
System.out.println(buf);
Prints AbcDefGhi, as expected.
It could be simplier, if you use Stream:
String res = Stream.of("ABC", "DEF", "GHI")
.map(WordUtils::capitalizeFully)
.collect(Collectors.joining(", ")); // if you want to split words with comma
Your code should work.
May I however suggest using a stream instead?
String concatenatedString = Arrays.stream(array)
.map(WordUtils::capitalizeFully)
.collect(Collectors.joining());
Which, with appropriate static imports fits well on one line without losing readability:
String concatenatedString = stream(array).map(WordUtils::capitalizeFully).collect(joining());
Note that joining() uses a StringBuilder iternally, so you don't need to worry about performance here. Also, joining() allows you to choose which string you want to delimit the content of the stream with, in this case I chose an empty string, which would result in AbcDefGhi.
This should do :
String[] stringToSplit = {"ABC", "DEF", "GHI"};
StringBuilder sb = new StringBuilder();
for(String s: stringToSplit) {
sb.append(s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase());
}
Update: I'm tired...
The first character was actually a [ from the array instead of "a", thus the a was never capitalized
Thanks all, and sorry for wasting your time
I am trying to parse an input string like this
String input = "((1,2,3),(3,4,5),(2,3,4),...)"
with the aim of getting an array of String where each element is an inner set of integers i.e.
array[0] = (1,2,3)
array[1] = (3,4,5)
etc.
To this end I am first of all getting the inner sequence with this regex:
String inner = input.replaceAll("\\((.*)\\)","$1");
and it works. Now I'd like to get the sets and I am trying this
String sets = inner.replaceAll("((\\((.*)\\),?)+","$1")
But I can't get the result I expected. What am I doing wrong?
Don't use replaceAll to remove the parentheses at the ends. Rather use String#substring(). And then to get the individual elements, again rather than using replaceAll, you should use String#split().
String input = "((1,2,3),(3,4,5),(2,3,4))";
input = input.substring(1, input.length() - 1);
// split on commas followed by "(" and preceded by ")"
String[] array = input.split("(?<=\\)),(?=\\()");
System.out.println(Arrays.toString(array));
I have a variable in java, which is like this I+am+good+boy I want to get seperate them on the basis of + , in PHP I can use explode which is very handy, is there any function in java?I saw the split() function definition but that was not helpful.as it take regular expression.
Any help
Thanks
Use String.split() in regards to explode.
An example of use:
Explode :
String[] explode = "I+am+a+good+boy".split("+");
And you can reverse this like so (or "implode" it):
String implode = StringUtils.join(explode[], " ");
You have two options as I know :
String text = "I+am+good+boy";
System.out.println("Using Tokenizer : ");
StringTokenizer tokenizer = new StringTokenizer(text, "+");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(" Token = " + token);
}
System.out.println("\n Using Split :");
String [] array = text.split("\\+");
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
You can try like this
String str = "I+am+a+good+boy";
String[] array = str.split("\\+");
you will get "I", "am", "a", "good", "boy" strings in the array. And you can access them as
String firstElem = array[0];
In the firstElem string you will get "I" as result.
The \\ before + because split() takes regular expressions (regex) as argument and regex has special meaning for a +. It means one or more copies of the string trailing the +.
So, if you want to get literal + sign, then you have to use escape char \\.
Just use split and escape the regex - either by hand or using the Pattern.quote() method.
String str = "I+am+a+good+boy";
String[] pieces = str.split("+")
Now you can use pieces[0], pieces[1] and so on.
More Info: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29