I have a string #JSGF V1.0;grammar numbers;public <accion> = (one| two| three);
I want the numbers: one, two and three.
I did this String answer = res.substring(res.indexOf("(")+1,res.indexOf(")")); and obtain one| two| three, but Im having trouble in this part.
Ideas?
You can get the numbers as array using
String numbers[] = answer.split("\\s*\\|\\s*");
\\s*\\|\\s*: 0 or more spaces then | symbol and 0 or more spaces
split the answer on non-word characters:
public static void main(String[] args) {
String res = "JSGF V1.0;grammar numbers;public <accion> = (one| two| three);";
String answer = res.substring(res.indexOf("(") + 1, res.indexOf(")"));
String[] numbers = answer.split("[^\\w]+"); // split on non-word character
for (String number : numbers) {
System.out.println(number);
}
}
output:
one
two
three
String res = "(one| two| three);";
String answer = res.substring(res.indexOf("(")+1,res.indexOf(")"));
for(String str : answer.split("\\s*\\|\\s*")) {
System.out.println(str);
}
Related
This is an interview which was asked recently.
Suppose there are 2 strings.
String a="test";
String b="lambda";
Reverse the String.
//tset
//adbmal
Expected output should be : tasdebtmal
Here we are trying to print characters from each string.
"t" from 1st String is printed, followed by "a" from other string, and so on.
So, "tasdebtm" is printed from each string and the remaining characters "al" is appended at the end.
int endA = a.length() - 1;
int endB = b.length() - 1;
StringBuilder str = new StringBuilder();
//add values to str till both the strings are not covered
while(endA>-1 && endB>-1){
str.append(a.charAt(endA--));
str.append(b.charAt(endB--));
}
add all chars of a if any is remaining
while(endA>-1){
str.append(a.charAt(endA--));
}
add all chars of b if any is remaining
while(endB>-1){
str.append(b.charAt(endB--));
}
System.out.println(str);
Definitely, there are other ways to do this too.
public class CharsinString2 {
public static void main(String[] args) {
String a="abra"; //arba
String b="kadabra";//arbadak // aarrbbaadak
int endA=a.length()-1;
int endB=b.length()-1;
StringBuilder str=new StringBuilder();
while(endA>-1 && endB>-1) {
str.append(a.charAt(endA--));
str.append(b.charAt(endB--));
}
while(endA>-1) {
str.append(a.charAt(endA--));
}
while(endB>-1) {
str.append(b.charAt(endB--));
}
System.out.println(str);
}
}
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?
I have to split a string which contain dash character and minus sign.
I tried to split based on the unicode character (https://en.wikipedia.org/wiki/Hyphen#Unicode), still it considering minus sign same as dash character. How van I solve it?
Expected output
(coun)
(US)
-1
Actual output
(coun)
(US)
// actually blank line will print here but SO editor squeezing the blank line
1
public static void main(String[] args) {
char dash = '\u002D';
int i = -1;
String a = "(country)" + dash + "(US)" + dash + i;
Pattern p = Pattern.compile("\u002D", Pattern.LITERAL);
String[] m = p.split(a);
for (String s : m) {
System.out.println(s);
}
}
I guess some conversion happens during the string concatenation but not sure.
Any suggestion to solve this issue is welcome
The operation dash + i is evaluated as numeric addition.
I think your string should be
String a = "(country)" + dash + "(US)" + dash + "" + i;
to produce the output you described.
#anubhava was partially right, I was using the wrong unicode.
I should have used "\u2010". Now everything working as expected.
public static void main(String[] args) {
char dash = '\u2010';
int i = -1;
char dashesd = '-';
String a = "(coun)"+dash+"(US)"+dash+i;
System.out.println(a);
Pattern p = Pattern.compile("\u2010", Pattern.LITERAL);
String [] m= p.split(a);
for (String s : m) {
System.out.println(s);
}
I am trying to separate the char from the following examples of inputs:
C450.00
C30
P100
I would like to have the char such as "C" or "P" separated so I can work with them alone,
as well as the "450.00", "30", and "100" separated as ints. What would be the easiest way to do this?
You can split the String with whitespace as delimiter. Afterwards use substring on every part of your string. Now you have the C and the 450.0 as Stings. Finally cast the second part of your substring into an integer and you are done.
to split:
String[] parts = string.split(" ");
to substring:
String first = parts[0].substring(0, 1);
String second = parts[0].substring(1);
If the String are always that format:
char ch = yourString.charAt(0);
Double d = Double.valueOf(yourString.substring(1, yourString.length()));
NOTE: I used a Double because you have dots . in the String. You can convert from double to int easily if you won't have any decimals. But that depends on your needings.
Assuming you know what are you looking for in the given String (eg. You know you are looking for the C character ) , you could use the Regex Pattern : https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
You can use this library org.apache.commons.lang3.StringUtils
http://commons.apache.org/proper/commons-lang/download_lang.cgi
public static String[] split(String str, String separatorChars)
String[] res = StringUtils.split("C450.00 C30 P100", "CP ");
for (String r : res) {
System.out.println(r);
}
I assume the separate 'numbers' are always in this format:
C130
P90
V2.0
that is, a single letter followed by a number (possibly with a floating point).
String input = "C450.00 C30 P100";
// First split the string by a space
String[] parts = input.split(" ");
for (String part : parts) {
// Get the character from the string
char ch = part.charAt(0);
// Get the remains of the string and convert it to a double
double number = Double.parseDouble(part.substring(1));
// Then do something with 'ch' and 'number'
}
If the separate parts possibly have two or more letters in it, e.g. AC130, then you need another approach:
String input = "AC130 AG36 P90";
String[] parts = input.split(" ");
for (String part : parts) {
/* Do some regular expression magic. */
}
See http://www.vogella.com/tutorials/JavaRegularExpressions/article.html.
here some piece of code:
public static void main(String[] args) {
String a = "C450.00 C30 P100";
String letters = "";
String numbers = "";
for (int i = 0; i < a.length(); i++) {
if ((a.charAt(i) + "").matches("\\d|\\.| ")) {
numbers += a.charAt(i);
} else {
letters += a.charAt(i);
}
}
String[] strArray = numbers.split(" ");
int[] numberArray = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
numberArray[i] = (int) Double.parseDouble(strArray[i]);
System.out.println(numberArray[i]);
}
System.out.println(letters);
}
the result is numberArray, which contains all numbers as ints.
and letters, which is a String with all letters.
Suppose I have two strings to "join" with a delimiter.
String s1 = "aaa", s2 = "bbb"; // input strings
String s3 = s1 + "-" + s2; // join the strings with dash
I can use s3.split("-") to get s1 and s2. Now, what if s1 or s2 contains dashes? Suppose also that s1 and s2 may contain any ASCII printable and I don't want to use non-printable characters as a delimiter.
What kind of escaping would you suggest in this case?
If I could define the format, delimiters, etc. I would use OpenCSV and use it's defaults.
You could use an uncommon character sequence, such as ;:; as a delimiter instead of a single character.
Here is another working solution, that doesn't use a separator, but that joins the lengths of the strings at the end of the imploded string to be able to re-explode it after:
public static void main(String[] args) throws Exception {
String imploded = implode("me", "and", "mrs.", "jones");
System.out.println(imploded);
String[] exploded = explode(imploded);
System.out.println(Arrays.asList(exploded));
}
public static String implode(String... strings) {
StringBuilder concat = new StringBuilder();
StringBuilder lengths = new StringBuilder();
int i = 0;
for (String string : strings) {
concat.append(string);
if (i > 0) {
lengths.append("|");
}
lengths.append(string.length());
i++;
}
return concat.toString() + "#" + lengths.toString();
}
public static String[] explode(String string) {
int last = string.lastIndexOf("#");
String toExplode = string.substring(0, last);
String[] lengths = string.substring(last + 1).split("\\|");
String[] strings = new String[lengths.length];
int i = 0;
for (String length : lengths) {
int l = Integer.valueOf(length);
strings[i] = toExplode.substring(0, l);
toExplode = toExplode.substring(l);
i++;
}
return strings;
}
Prints:
meandmrs.jones#2|3|4|5
[me, and, mrs., jones]
Why don't you just store those strings in an array and join them with dash each time you want to display them to user?