Trying to split using comma as a delimiter in the string and add into a string array, but facing problem while spliting the string using regex.
String[] stringParts = str1.split(",(?![^\\[]*\\])");
for (int i=0; i<stringParts.length; i++){
stringParts[i] = stringParts[i].trim();//remove trailing leading spaces.
}
//System out
for (String s:stringParts){
System.out.println(s);
}
Input String
String str="1, two, {\"\"Customization\"\":{\"\"EMPLOYEEID\"\":\"\"EMPID001\"\",\"\"MANAGER_ID\"\":\"\"MNGID001\"\",\"\"DEPARTMENT\"\":\"\"IT\"\"},\"\"OTHERDETAILS\"\":{\"\"GENDER\"\":\"\"M\"\",\"\"DESIGNATION\"\":\"\"SENIOR\"\",\"\"TEAM\"\":\"\"QA\"\"}}, 8, nine,{{\"COMPANYNAME\":\"XYZ Ind Pvt Ltd\"},{[ten,{\"11\":\"12\"},{\"thirteen\":14}]}},\"fifteen\",16";
Required Output
1
two
{""Customization"":{""EMPLOYEEID"":""EMPID001"",""MANAGER_ID"":""MNGID001"",""DEPARTMENT"":""IT""},""OTHERDETAILS"":{""GENDER"":""M"",""DESIGNATION"":""SENIOR"",""TEAM"":""QA""}}
8
nine
{{"COMPANYNAME":"XYZ Ind Pvt Ltd"},{[ten,{"11":"12"},{"thirteen":14}]}}
fifteen
16
This isn't something that regex is designed for. You need to create a parser.
Or you could do something similar to this:
public static void main(String[] args) {
String str = "1, two, {\"\"Customization\"\":{\"\"EMPLOYEEID\"\":\"\"EMPID001\"\",\"\"MANAGER_ID\"\":\"\"MNGID001\"\",\"\"DEPARTMENT\"\":\"\"IT\"\"},\"\"OTHERDETAILS\"\":{\"\"GENDER\"\":\"\"M\"\",\"\"DESIGNATION\"\":\"\"SENIOR\"\",\"\"TEAM\"\":\"\"QA\"\"}}, 8, nine,{{\"COMPANYNAME\":\"XYZ Ind Pvt Ltd\"},{[ten,{\"11\":\"12\"},{\"thirteen\":14}]}},\"fifteen\",16";
StringTokenizer st = new StringTokenizer(str, ",", true);
int bracketCount = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken();
long brackets = token.chars().map(ch -> (ch == '{' ? 1 : (ch == '}' ? -1 : 0))).sum();
bracketCount += brackets;
if (bracketCount == 0 && ",".equals(token)) {
System.out.println("");
} else {
System.out.print(token);
}
}
}
Take the string and split on ,, keeping the delimiter as an output token
count the number of open and close { }. Ensure all brackets have been closed.
If all { } have been closed then move onto the next line
Related
for a class assignment, I'm using data from https://www.kaggle.com/shivamb/netflix-shows which has presented a small problem for me:
it is a CSV, however, the cast variable was also separated by commas affecting the .split function I was using. the data has a set of [value, value, value," value,value ", value, ...]. the goal is to exclude the values within the " ".
currently to run this function I have:
while ( inFile.hasNext() ){
String delims = "[,]"; //Delimiters for seperation
String[] tokens = inFile.nextLine().split(delims); // seperation operator put in to string array
for (String token : tokens) {
System.out.println(token);
}
Because it's a class assignment, I would simple just code the logic.
For each character decide if you want to add it to a current word or if a new word has to start. So its pretty easy to store if you are in the " " and react on this..
something like this
public List<String> split(String line)
{
List<String> result = new ArrayList<>();
String currentWord = "";
boolean inWord = false;
for (int i = 0; i < line.length(); i++)
{
char c = line.charAt(i);
if (c == ',' && !inWord)
{
result.add(currentWord.trim());
currentWord = "";
continue;
}
if (c == '"')
{
inWord = !inWord;
continue;
}
currentWord += c;
}
return result;
}
there are some hard core regular expressions like here: Splitting on comma outside quotes
but I would not use them in an assignment.
I'm sure there is a simpler way of doing this but this is one solution I came up with.
while ( inFile.hasNext() ) {
int quote = 0;
String delims = "[,]"; //Delimiters for seperation
String[] tokens = inFile.nextLine().split(delims);
for (String token : tokens) {
if(token.contains("\"")) { //If contains a quote
quote++; //Increment quote counter
}
if (quote != 1) //If not between quotes
{
if(token.indexOf(" ") == -1) //Print if no space at beginning
{
System.out.println(token);
}
else { //Print from first character
System.out.println(token.substring(token.indexOf(" ") + 1));
}
}
}
}
inFile.close();
My problem is that I'm getting a String and I need to check if there is a space in the 4th position but starting from the end. If in this position there is not a space, I should insert it.
For example:
I get this String: TW12EF, need to get it like this: TW1 2EF
First of all I get the 4 last characters in a char array because I also need to check if they are numbers or letters.
With this method I check if there is a space:
public static boolean isSpace(){
return String.valueOf(charArray[0]).matches("[ \\t\\n\\x0B\\f\\r]");
}
charArray contains the last 4 characters of the input String
If charArray[0] wouldn't be a space, I want to insert a space in the 2nd place (charArray[1])
If there is something that I can correct in the question to make it easier to understand, just let me know and I will try to make it better for next questions.
A simple and direct solution (most likely faster than using a regular expression) is to get the 4th to the last character (if it exists), and if it isn't a white-space, insert a space at that position.
public static void main(String[] args) {
String str = "TW12EF";
int insertPos = str.length() - 4;
if (insertPos >= 0) {
char ch = str.charAt(insertPos);
if (!Character.isWhitespace(ch)) {
str = new StringBuilder(str).insert(insertPos + 1, ' ').toString();
}
}
System.out.println(str);
}
A whitespace is determined by invoking isWhitespace, which returns true for space but also tabs or line feeds, like you did in your question. The character is inserted by leveraging the StringBuilder#insert method, which is more direct that taking 2 substrings and concatenating them.
A quick, dirty regex will help :
String p = "TW12EF";
System.out.println(p.replaceAll("(.)\\s*(\\S.{2})$", "$1 $2")); // Select a character followed by 0 or more spaces and followed by 3 non-space characters. And replace multiple spaces if they exist with a single space
O/P :
TW1 2EF
Also works if there are one or more spaces after the 3rd char (from the left)
As char is a primitive data type, the comparison can be done simply with
if (charArray[0] == ' ') {
char[] temp = new char[5];
temp[0] = ' ';
for (int i = 1; i <= 4; i++) {
temp[i] = charArray[i - 1];
}
charArray = temp;
}
You could use something like:
public static void main(String[] args) {
String str = "TW12EF";
processStr(str);
}
public static final int SPACE_POS = 4, OFFSET = 1;
public static String processStr(String str)
{
if(!Character.isWhitespace(str.charAt(str.length() - SPACE_POS)))
{
str = String.format("%s %s", str.substring(0, str.length() - SPACE_POS + OFFSET), str.substring(SPACE_POS - OFFSET));
}
return str;
}
Like this?
` String s="TW12EF";
String result="";
int length=s.length();
for(int i=length-1;i>-1;i--){
if(i==length-4&&s.charAt(i)!=' '){
result+=" ";
}
result+=s.charAt(length-i-1);
}
System.out.println(result);`
How do i convert a string like below
String str="[in,us,eu,af,th]";
into
["in","us","eu","af","th"]
Just use String functions:
str = str.substring(1,str.length()-2); // remove brackets
String a[] = str.split(","); //split it.
String result = str.replace("[", "[\"").replace(",", "\",\"").replace("]", "\"]");
public static void main(String[] args) {
String str = "[in,us,eu,af,th]";
str = str.substring(1, str.length() - 1);
// #1 remove starting and ending brackets
System.out.println("String without brackets : " + str);
//#2 split by comma
String[] stringTokens = str.split(",");
StringBuffer outputStrBuffer = new StringBuffer();
outputStrBuffer.append("["); // append starting square bracket
for (int i = 0; i <= stringTokens.length - 1; i++) {
//prefix and postfix each token with double quote
outputStrBuffer.append("\"");
outputStrBuffer.append(stringTokens[i]);
outputStrBuffer.append("\"");
// for last toke dont append comma at end
if (i != stringTokens.length - 1) {
outputStrBuffer.append(",");
}
}
outputStrBuffer.append("]"); // append ending square bracket
System.out.println("String prefixed & postfixed with double quotes, separated by comma : " + outputStrBuffer.toString());
}
This question already has answers here:
Reverse a given sentence in Java
(14 answers)
Closed 7 years ago.
Given a String with words.Reverse words of String.
Sample Input 1
Hello World
Sample Output
World Hello
MyApproach
To reverse words I first counted how many spaces are there.After that I stored their space index in an array.Using lastIndex, I printed the last elements of the array.After that I printed the last 2 words of the array.
static String reverseWords(String inputString)
{
int l1=inputString.length();
int count=1;
for(int i=0;i<l1;i++)
{
char ch=inputString.charAt(i);
if(ch==' ')
{
count++;
}
}
int k=0;
int[] spaceindex=new int[count];
spaceindex[0]=0;
k++;
for(int i=0;i<l1;i++)
{
char ch=inputString.charAt(i);
if(ch==' ')
{
spaceindex[k++]=i+1;
}
}
int p=spaceindex.length-1;
String strnew="";
for(int j=spaceindex[p];j<l1;j++)
{
char c=inputString.charAt(j);
strnew=strnew+c;
}
p--;
while(p>=0)
{
for(int j=spaceindex[p];;j++)
{
char c=inputString.charAt(j);
if(c==' ')
{
break;
}
strnew=strnew+c;
}
}
return strnew;
}
InputParameters ActualOutput Expected Output
Hello World WorldHelloWorldHello(Infinite loop) WorldHello
#Edit I asked Why the code I wrote is wrong.I tried without using any inbuilt functions(which was necessary for me).In that way I think It is not Duplicate Ans according to me.
Can anyone guide me what went wrong in my code.
The issue within your code was the while loop:
while(p>=0) {
strnew = strnew + " ";
for(int j=spaceindex[p];;j++) {
char c=inputString.charAt(j);
if(c==' '){
break;
}
strnew=strnew+c;
}
p--;
}
Adding the p-- will prevent the loop for occurring infinitely. Also inserting the strnew = strnew + " "; after the while loop ensures a space in between each word.
It's possible without using another arrays, splits or any additional strucure.
Having array of characters ( convert if needed as String is immutable), first reverse all characters in the array. Secondly loop over spaces and for each word reverse characters in the word.
Simple solution :
public static void main(String[] args) {
String x = "Hello World";
String[] xArray = x.split(" ");
String result = "";
for (int i = xArray.length - 1; i >= 0; i--) {
result += xArray[i] + " ";
}
System.out.println(result.trim()); // World Hello
}
You can use a StringTokenizer to convert the string into tokens or String.split function. You can push this collection into a Stack and extract the elements in a reverse order. To join the strings back you could use a StringBuilder or a StringBuffer.
To do this more efficiently you could convert the string to a character array and StringBuilders
String myString = "Here is the String";
char[] myChars = myString.toCharArray();
StringBuilder word = new StringBuilder();
StringBuilder newString = new StringBuilder();
for(int i = myChars.length - 1; --i >= 0;) {
char c = myChars[i];
if(c == ' ') {
newString.append(c);
newString.append(word);
word = new StringBuilder();
} else {
word.append(c);
}
}
I would base an implementation on String.lastIndexOf(int) and String.substring(int, int). I'd got with a StringBuilder to construct the output "sentence" and a while loop to iterate the words in reverse order. Something like,
static String reverseWords(String in) {
StringBuilder sb = new StringBuilder(in.length());
int space;
while ((space = in.lastIndexOf(' ')) > 0) {
sb.append(in.substring(space + 1, in.length())).append(' ');
in = in.substring(0, space);
}
sb.append(in);
return sb.toString();
}
Which I tested with your provided sample
public static void main(String[] args) {
System.out.println(reverseWords("Hello World"));
}
Getting (as expected)
World Hello
Below code has variable "name". This may contain first and last name or only first name. This code checks if there is any white space in variable "name". If space exists, then it splits.
However, I am getting the "Error : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at Space.main(Space.java:9)" during below cases
If there is a white space before "Richard"
If there is a white space after "Richard" without second word or second string.
If I have two spaces after "Richard" then it will not save the name in lname variable.
How to resolve this error.
public class Space {
public static void main(String[] args) {
String name = "Richard rinse ";
if(name.indexOf(' ') >= 0) {
String[] temp;
temp = name.split(" ");
String fname = temp[0];
String lname = temp[1];
System.out.println(fname);
System.out.println(lname);
} else {
System.out.println("Space does not exists");}
}
}
you have to split a string using "\s" like this
name.split("\\s+");
If there are two spaces temp[1] will be empty, given "Richard rinse" the array is split this way
1 Richard
2
3 rinse
You should trim() the string and do something like
while(name.contains(" "))
name=name.replace(" "," ");
String[] parts = name.trim().split("\\s+");
if (parts.length == 2) {
// print names out
} else {
// either less than 2 names or more than 2 names
}
trim removes leading and trailing whitespace as this lead to either leading or trailing empty strings in the array
the token to split on is a regular expression meaning any series of characters made up of one or more whitespace characters (space, tabs, etc...).
Maybe that way:
public class Space {
public static void main(String[] args) {
String name = "Richard rinse ";
String tname = name.trim().replace("/(\\s\\s+)/g", " ");
String[] temp;
temp = name.split(" ");
String fname = (temp.length > 0) ? temp[0] : null;
String lname = (temp.length > 1) ? temp[1] : null;
if (fname != null) System.out.println(fname);
if (lname != null) System.out.println(lname);
} else {
System.out.println("Space does not exists");
}
}
To trim the white spaces, use this.
public String trimSpaces(String s){
String str = "";
boolean spacesOmitted = false;
for (int i=0; i<s.length; i++){
char ch = s.chatAt(i);
if (ch!=' '){
spacesOmitted = true;
}
if (spacesOmitted){
str+=ch;
}
}
return str;
}
Then use the trimmed string in the place of name.