I am having troubles splitting this string into the different values.
When splitting it using R, there is no problem splitting it using sep="\t".
But in Java I cannot make it work.
I copied the string from the file that I am reading from and it seems to be reproducible in the online java fiddlers.
I've already tried "\s+", "\t+", "\t", "\t", "\t+".
Maybe the String is not tab delimited? But why does R work then?
public class JavaFiddle {
static String s = " 1 0 3 150.00";
public static void main(String[] args) {
System.out.println(s.split("\\t+")[0]);
}
}
I think you can use the \\s :
public class JavaFiddle {
static String s = " 1 0 3 150.00";
public static void main(String[] args) {
String[] split = s.trim().split("\\s+");
for(int i=0; i < split.length; i++){
System.out.println(i + "-->" + split[i]);
}
}
}
And the output is:
0-->1
1-->0
2-->3
3-->150.00
Related
I'm trying to print out a string with spaces on either side of each char in the string
so if I have
String s = "abcde"
it would create something like this
a b c d e
with a space before the first char and three between each char.
I just haven't been able to find a way to do this with my knowledge.
Update
Updated requirement:
I failed to realize that I need something that add one place in front
of the first term and then 3 spaces between each term.
_0___0___0___0___0_ for example.
For the updated requirement, you can use yet another cool thing, String#join.
public class Main {
public static void main(String[] args) {
String s = "abcde";
String result = "_" + String.join("___", s.split("")) + "_";
System.out.println(result);
}
}
Output:
_a___b___c___d___e_
Original answer
There can be so many ways to do it. I find it easier to do it using Regex:
public class Main {
public static void main(String[] args) {
String s = "abcde";
String result = s.replaceAll(".", " $0 ");
System.out.println(result);
}
}
Output:
a b c d e
The Regex, . matches a single character and $0 replaces this match with space + match + space.
Another cool way is by using Stream API.
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String s = "abcde";
String result = Arrays.stream(s.split(""))
.map(str -> " " + str + " ")
.collect(Collectors.joining());
System.out.println(result);
}
}
Output:
a b c d e
A super simple example, that doesn't handle a multitude of potential input scenarios.
public static void main(String[] args)
{
String s = "abcde";
for (int i = 0; i < s.length(); ++i) {
System.out.print("_" + s.charAt(i));
}
System.out.println("_");
}
NOTE: used an underscore rather than a space in order to allow visual check of the output.
Sample output:
_a_b_c_d_e_
Rather than direct output, one could use a StringBuilder and .append to a builder instead, for example.
Using StringBuilder:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ++i) {
sb.append('_').append(s.charAt(i));
}
sb.append('_');
System.out.println(sb.toString());
Based on a comment where the desired output is slightly different (two internal spaces, one leading and trailing space), this suggests an alternative approach:
public static String addSpace(String inp) {
StringBuilder sB = new StringBuilder();
String string = inp.trim();
String div = "___"; // spaces, or whatever
sB.append('_'); // add leading space
for(int index = 0; index < string.length(); ++index) {
sB.append(string.charAt(index))
.append(div); // two spaces
}
sB.setLength(sB.length() - (div.length() - 1) );
return (sB.toString());
}
NOTE: again using an underscore to allow for easier debugging.
Output when div is set to 3 underscores (or spaces):
_0___0___0___1___0___1___1___0_
You can define an empty string : result = “”;
Then go through the string you want to print with foreach loop With the function toCharArray()
(char character : str.toCharArray())
And inside this loop do ->
result += “ “ + character;
String result = s.chars().mapToObj(
Character::toString
).collect(Collectors.joining(" "));
Similar to the loop versions, but uses a Stream.
Another one liner to achieve this, by splitting the String into String[] of characters and joining them by space:
public class Main {
public static void main(String[] args) {
String s = "abcde";
System.out.println(" " + String.join(" ", s.split("")) + " ");
}
}
Output:
a b c d e
Edit:
The above code won't work for strings with Unicode codepoints like "👦ab😊", so instead of splitting on empty string, the split should be performed on regex: "(?<=.)".
public class Main {
public static void main(String[] args) {
String s = "abcde";
System.out.println(" " + String.join(" ", s.split("(?<=.)")) + " ");
}
}
Thanks to #saka1029 for pointing this out.
You can use Collectors.joining(delimiter,prefix,suffix) method with three parameters:
String s1 = "abcde";
String s2 = Arrays.stream(s1.split(""))
.collect(Collectors.joining("_+_", "-{", "}-"));
System.out.println(s2); // -{a_+_b_+_c_+_d_+_e}-
See also: How to get all possible combinations from two arrays?
suppose we have
String str = "Hello-Hello1";
How do we split it and compare it to see if it is equal or not?
This is what I wrote, but it does not give me the result.
public static void main(String[] args) {
String str = "Hello-Hello1";
String [] a = str.split("-");
for(int i=0; i<a.length; i++) {
System.out.print(a[i]+ " ");
}
for(int first =0; first<a.length; first++) {
for(int second =first+1; second<a.length; second ++) {
if(a[first].equals(a[second])){
System.out.println(a[first]);
}
}
}
}
First, you split your string like shown here:
How to split a string in Java, then compare them using the equals method: a[0].equals(a[1]);
Thank you all for helping
Here is the answer
public class SplitStringAndCompare {
public static void main(String[] args) {
String str = "Hello-Hello1";
String [] a = str.split("-");
if(a[0].equals(a[1])) {
System.out.println(a[0]+ " is equal to " + a[1]);
} else {
System.out.println(a[0]+ " is not equal to "+ a[1]);
}
}
Today I am trying to convert String to reverse String e.g(Cat Is Running into Running Is Cat) word by word not Character
public class ReverseString_ {
public static void reverse(String str) {
String[] a = str.split(" ");
for (int i = a.length - 1; i >= 0; i--) {
System.out.println(a[i] + " ");
}
}
public static void main(String[] args) {
reverse("Cat Is Running");
}
}
The following output is shown:
Running Is Cat BUILD SUCCESSFUL (total time: 0 seconds)
I am trying to convert String into reverse String same as above but through Recursion method but it seems too confusing. and display more errors. Can someone please help me understanding it. Many thanks
public static String reverse_recursion(String str) {
if (str == null)
return null;
else {
String Arry[] = str.split(" ");
int n = Arry.length - 1;
System.out.println(Arry[n] + "");
return reverse_recursion(Arry[n - 1]);
}
}
public static void main(String[] args) {
reverse_recursion("Cat Is Running");
}
This code show following output:
Running
Is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
This code do not print (0) index why? can someone help me to solve this error please
This solution might be helpful. The comments explain the code pretty much.
public static String reverse_recursion(String str) {
String[] arry = str.split(" ", 2); //Split into a maximum of 2 Strings
if (arry.length > 1) { //If there is more than 1 word in arry
//Return the reverse of the rest of the str (arry[1])
//and concatenate together with the first word (arry[0])
return reverse_recursion(arry[1]) + " " + arry[0];
}
return arry[0]; //If less than or equal to 1 word, just return that word
}
This should work:
public static String reverse(String s) {
int idx = s.indexOf(" ");
if (idx < 0) {
// no space char found, thus, s is just a single word, so return just s itself
return s;
} else {
// return at first the recursively reversed rest, followed by a space char and the first extracted word
return reverse(s.substring(idx + 1)) + " " + s.substring(0, idx);
}
}
public static void main(String[] args) {
System.out.println(reverse("Cat Is Running"));
}
You are sending the last element of the Array next time instead of the String without the previously printed String.
Replace your return statement with this it should work.
return reverse_recursion(n==0?null:str.substring(0,(str.length()-Arry[n].length())-1));
I need "args[i]" to be converted to Uppercase so the output will be:
"$ARG1" line break
"$ARG2" line break
"$ARG3" line break
and so on. I need to use the "toUpperCase" method but don't know how.
public class Main {
public static void main(String[] args) {
System.out.println("Number of args:" +
args.length);
for(int i=0; i<args.length; i++){
char dollar = '\u0024';
System.out.println(dollar + args[i]);
}
}
}
Java has this functionality built into the String object like so:
System.out.println(dollar + args[i].toUpperCase());
See the Oracle documentation here
Just use .toUpperCase() on any String, and it will return an all-upper-case String.
System.out.println(dollar + args[i].toUpperCase());
java has String method :public String toUpperCase()
public class Main {
public static void main(String[] args) {
System.out.println("Number of args:" + args.length);
for(int i=0; i<args.length; i++){
char dollar = '\u0024';
System.out.println(dollar + args[i].toUpperCase());
}
}
}
See the Oracle documentation here
public class Main {
public static void main(String[] args) {
System.out.println("Number of args:" +
args.length);
char dollar = '\u0024';
for(int i=0; i<args.length; i++){
System.out.println(dollar + args[i].toUpperCase());
}
}
}
I have an encoded String like this:
17298457,abcdef/17298529,ghijklm/17298562,opq%2Frstu
and want to split it on the "/".
In the last part, there is a encoded "/" as "%2F".
The result is
[17298457,abcdef , 17298529,ghijklm , 17298562,opq , rstu]
The problem is, that Java decodes the string on the fly as soon as i pass it to another method (split method e.c.)
Do someone have a good idea how to work around that?
thanks a lot!
monk
Not for me....
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws Exception {
String s = "17298457,abcdef/17298529,ghijklm/17298562,opq%2Frstu";
System.out.println(Arrays.toString(s.split("/")));
}
}
gives
[17298457,abcdef, 17298529,ghijklm, 17298562,opq%2Frstu]
public static void main(String[] args) {
String test = "17298457,abcdef/17298529,ghijklm/17298562,opq%2Frstu";
String[] args2 = test.split("/");
for (int i = 0; i < args2.length; i++) {
String[] args3 = args2[i].split("%2F");
for (int j = 0; j < args3.length; j++) {
if(!args3[j].trim().startsWith(",") && j != 0)
System.out.print(" ,");
System.out.print(args3[j]);
}
}
OUT PUT - AS U WRITTEN -
17298457,abcdef17298529,ghijklm17298562,opq ,rstu