How to Split String in "" after comma (,) - java

If I have String string = "[10.10, 20.20, 30.30]";
How to split into this format ["10.10", "20.20", "30.30"]

Before splitting, you need to take away the brackets, using substring
String string = "[10.10, 20.20, 30.30]";
String[] res = string.substring(1, string.length() - 1).split(",\\s");
System.out.println(Arrays.toString(res)); // [10.10, 20.20, 30.30]

Do it as follows:
public class Main {
public static void main(String[] args) {
String string = "[10.10, 20.20, 30.30]";
String[] arr = string.replace("[", "").replace("]", "").split(",");
for (int i = 0; i < arr.length; i++) {
arr[i] = "\"" + arr[i].trim() + "\"";
}
String newStr = "[" + String.join(", ", arr) + "]";
System.out.println(newStr);
}
}
Output:
["10.10", "20.20", "30.30"]
If you have a String[] to convert, you can do it as follows:
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
public static void main(String args[]) {
String[] strArr = { "10.10", "20.20", "30.30" };
System.out.println("Before: " + Arrays.toString(strArr));
strArr = Arrays.stream(strArr).map(s -> "\"" + s + "\"").collect(Collectors.toList()).toArray(new String[0]);
System.out.println("After: " + Arrays.toString(strArr));
}
}
Output:
Before: [10.10, 20.20, 30.30]
After: ["10.10", "20.20", "30.30"]
[Update]
Posting the following update based on the requirement mentioned by OP in the comment:
public class Main {
public static void main(String[] args) {
String str = "10.10,20.20,30.30";
str = "[" + str.replaceAll("[0-9.-]+", "\"$0\"") + "]";
System.out.println(str);
}
}
Output:
["10.10","20.20","30.30"]

Related

How to replace a word based on its length?

All words having the given length wordLength in the string sentence must be replaced with the word myWord. All parameters come from user input and may vary. I have tried this way but it only returns the initial string with the initial words.
Here is my source code:
package main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
String sentence = "";
int wordLength = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLength = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
Text myText = new Text(myWord, sentence, wordLength);
myText.changeSentence();
System.out.println("New string" + myText.getSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getSentence() {
return newSentence;
}
public void changeSentence() {
int firstPos = 0;
int i;
for (i = 0; i < mySentence.length(); i++) {
if (mySentence.charAt(i) == ' ') {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
} else if (i == mySentence.length() - 1) {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
}
}
}
}
I changed your code a little bit:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
String sentence = "";
int wordLenght = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
try {
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLenght = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Text myText = new Text(myWord, sentence, wordLenght);
System.out.println(myText.getChangeSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getChangeSentence() {
String[] words = mySentence.split(" ");
for(int i = 0 ; i < words.length ; i++) {
if(words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
for (String word : words) {
newSentence += word + " ";
}
return newSentence;
}
}
Input : This is a test
word length : 2
word to replace : ii
output: This ii a test
As I can see the only separator of words that is currently considered to appear in the input text is a single white space " ". If that's true, then the changeSentence method can be quite short. There is no need to do parse the sentence character by characted. Having in mind that the white space is a separator, you can simply split the sentence by the characted " " and collect them as words. After that you can just iterate through words and replace ones that lenght matches given input characters number. After that, you can just join words together with the previously used separator and that's it.
Examples if you want to try with loops
public void changeSentence() {
final String[] words = mySentence.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
newSentence = String.join(" ", words);
}
or with regular expressions
public void changeSentence() {
String regex = "\\b\\w{" + charNumber+ "}\\b";
newSentence = mySentence.replaceAll(regex, wordToChange);
}
or with the stream API
public void changeSentence() {
newSentence = Arrays.stream(mySentence.split(" "))
.map(s -> s.length() == charNumber ? wordToChange : s)
.collect(Collectors.joining(" "));
}

Remove some text between square brackets in Java 6

Would it be possible to change this:
[quote]user1 posted:
[quote]user2 posted:
Test1
[/quote]
Test2
[/quote]
Test3
to this:
Test3
Using Java 6?
ok, wrote some not regex solution.
String str ="[quote]user1 posted:[quote]user2 posted:Test1[/quote]Test2[/quote]Test3";
String startTag = "[quote]";
String endTag = "[/quote]";
String subStr;
int startTagIndex;
int endTagIndex;
while(str.contains(startTag) || str.contains(endTag)) {
startTagIndex = str.indexOf(startTag);
endTagIndex = str.indexOf(endTag) + endTag.length();
if(!str.contains(startTag)) {
startTagIndex = 0;
}
if(!str.contains(endTag)) {
endTagIndex = startTagIndex + startTag.length();
}
subStr = str.substring(startTagIndex, endTagIndex);;
str = str.replace(subStr, "");
}
I compiled this to Java 8. I don't believe I'm using any features not available in Java 6.
Edited: System.lineSeparator() was added in Java 1.7. I changed the line to
System.getProperty("line.separator").
public class RemoveQuotes {
public static void main(String[] args) {
String input = "[quote]user1 posted:\r\n" +
" [quote]user2 posted:\r\n" +
" Test1\r\n" +
" [/quote]\r\n" +
" Test2\r\n" +
"[/quote]\r\n" +
"Test3";
input = input.replace(System.getProperty("line.separator"), "");
String endQuote = "[/quote]";
int endPosition;
do {
int startPosition = input.indexOf("[quote]");
endPosition = input.lastIndexOf(endQuote);
if (endPosition >= 0) {
String output = input.substring(0, startPosition);
output += input.substring(endPosition + endQuote.length());
input = output;
}
} while (endPosition >= 0);
System.out.println(input);
}
}

String replace not working or Im dumb?

I have this:
for (String[] aZkratkyArray1 : zkratkyArray) {
String oldString = " " + aZkratkyArray1[0] + " ";
String firstString = aZkratkyArray1[0] + " ";
String newString = " " + aZkratkyArray1[1] + " ";
System.out.println(newString);
System.out.println(fileContentsSingle);
fileContentsSingle = fileContentsSingle.replaceAll(oldString, newString);
if (fileContentsSingle.startsWith(firstString)) {
fileContentsSingle = aZkratkyArray1[1] + " " + fileContentsSingle.substring(firstString.length(),fileContentsSingle.length());
}
}
fileContentsSingle is just some regular string, aZkratkyArray is array with shortened words, f.e.:
ht, hello there
wru, who are you
So when fileContentsSingle = ht I am robot
it should end up : hello there I am robot
or when fileContentsSingle = I am robot hru
it should end up : I am robot who are you
But when I sysout fileContentsSingle after this iteration, or during it, string is never changed.
I tried both replace and replaceAll, I tried probably everything I could think of.
Where is the mistake?
EDIT:
This is how I import array:
String[][] zkratkyArray;
try {
LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("zkratky.csv"));
lineNumberReader.skip(Long.MAX_VALUE);
int lines = lineNumberReader.getLineNumber();
lineNumberReader.close();
FileReader fileReader = new FileReader("zkratky.csv");
BufferedReader reader = new BufferedReader(fileReader);
zkratkyArray = new String[lines + 1][2];
String line;
int row = 0;
while ((line = reader.readLine()) != null) {
String[] array = line.split(",");
for (int i = 0; i < array.length; i++) {
zkratkyArray[row][i] = array[i];
}
row++;
}
reader.close();
fileReader.close();
} catch (FileNotFoundException e) {
System.out.println("Soubor se zkratkami nenalezen.");
zkratkyArray = new String[0][0];
}
Your code will work correctly for "ht I am robot". If you print fileContentsSingle after your for loop, it will print what you expect it to print:
final String[][] zkratkyArray = new String[2][];
zkratkyArray[0] = new String[] { "ht", "hello there" };
zkratkyArray[1] = new String[] { "wru", "who are you" };
String fileContentsSingle = "ht I am robot";
for (String[] aZkratkyArray1 : zkratkyArray) {
String oldString = " " + aZkratkyArray1[0] + " ";
String firstString = aZkratkyArray1[0] + " ";
String newString = " " + aZkratkyArray1[1] + " ";
fileContentsSingle = fileContentsSingle.replaceAll(oldString, newString);
if (fileContentsSingle.startsWith(firstString)) {
fileContentsSingle = aZkratkyArray1[1] + " "
+ fileContentsSingle.substring(firstString.length(), fileContentsSingle.length());
}
}
System.out.println(fileContentsSingle); // prints "hello there I am robot"
Concerning "I am robot hru", it will not work because "hru" is at the end of the String, and not followed by a space, and the String you are replacing is " hru " (with spaces before and after).
As you don't use regexps, you don't need replaceAll(), and you can use replace() instead.
Using regexps, you can do a more generic solution working everywhere in the line:
final String[][] zkratkyArray = new String[2][];
zkratkyArray[0] = new String[] { "ht", "hello there" };
zkratkyArray[1] = new String[] { "wru", "who are you" };
String fileContentsSingle = "ht I am robot wru";
for (String[] aZkratkyArray1 : zkratkyArray) {
fileContentsSingle = fileContentsSingle.replaceAll("\\b" + Pattern.quote(aZkratkyArray1[0]) + "\\b",
Matcher.quoteReplacement(aZkratkyArray1[1]));
}
System.out.println(fileContentsSingle); // hello there I am robot who are you
I don't think you are using any regex here. You are just reading a suustring and replace it with another one.
Just use the other version which does not use regex:
fileContentsSingle.replace(oldString, newString);
In the end, I found out that I had BOM's in input.csv file.

Algorithm to split string with comma only in the outer braces

I want to split string only inside the first braces. How can I do it in java
Input String 1: text2(text3, text4), text5(text6, text7)
String1: text2(text3, text4)
String2: text5(text6, text7)
Input String 2: text2, text3(text4, text5(text6, text7, text8))
String1: text2
String2: text3(text4, text5(text6, text7, text8))
Input String can have arbitrary number of levels. Please assume that the input string has matching braces.
Thanks in advance
package ic.ac.uk.relationshipvisualiser.app;
import java.util.ArrayList;
import java.util.List;
public class tmpTest3 {
public static List<String> process(String p_inp) {
List<String> res = new ArrayList<String>();
p_inp = p_inp.trim();
int numberOfOpenBracketsEncountered = 0;
String t = "";
String cur = "";
for (int c=0;c<p_inp.length();c++) {
cur = p_inp.substring(c,c+1);
if (cur.equals("(")) {
numberOfOpenBracketsEncountered++;
}
if (cur.equals(")")) {
numberOfOpenBracketsEncountered--;
}
if (cur.equals(",")) {
if (numberOfOpenBracketsEncountered==0) {
if (t.length()>0) res.add(t.trim());
t = "";
} else {
cur = cur;
t = t + cur;
}
} else {
cur = cur;
t = t + cur;
}
}
if (t.length()>0) res.add(t.trim());
return res;
}
public static void main(String[] args) {
System.out.println("Start tmpTest3");
List<String> inputs = new ArrayList<String>();
inputs.add("text2(text3, text4), text5(text6, text7)");
inputs.add("text2, text3(text4, text5(text6, text7))");
for (int c=0;c<inputs.size();c++) {
System.out.println("Running test for " + inputs.get(c));
List<String> res = process(inputs.get(c));
System.out.println("Got " + res.size() + " strings as a result:");
for (int d=0;d<res.size();d++) {
System.out.println(" - :" + res.get(d) + ":");
}
System.out.println("----------------------");
}
System.out.println("End tmpTest3");
}
}
Will This works for you ..?
import java.util.Arrays;
class Program {
public static void main (String[] args) throws java.lang.Exception {
String subject1 = "text2(text3, text4), text5(text6, text7)";
String subject2 = "text2, text3(text4, text5(text6, text7))";
String p = "\\s*\\d*\\(\\)";
String[] res = subject1.split(p);
System.out.println(Arrays.toString(res));
res=subject2.split(p);
System.out.println(Arrays.toString(res));
} // end main
} // end
Out put :-
[text2(text3, text4), text5(text6, text7)]
[text2, text3(text4, text5(text6, text7))]

Split mathematical string in Java

I have this string: "23+43*435/675-23". How can I split it? The last result which I want is:
String 1st=23
String 2nd=435
String 3rd=675
String 4th=23
I already used this method:
String s = "hello+pLus-minuss*multi/divide";
String[] split = s.split("\\+");
String[] split1 = s.split("\\-");
String[] split2 = s.split("\\*");
String[] split3 = s.split("\\/");
String plus = split[1];
String minus = split1[1];
String multi = split2[1];
String div = split3[1];
System.out.println(plus+"\n"+minus+"\n"+multi+"\n"+div+"\n");
But it gives me this result:
pLus-minuss*multi/divide
minuss*multi/divide
multi/divide
divide
But I require result in this form
pLus
minuss
multi
divide
Try this:
public static void main(String[] args) {
String s ="23+43*435/675-23";
String[] ss = s.split("[-+*/]");
for(String str: ss)
System.out.println(str);
}
Output:
23
43
435
675
23
I dont know why you want to store in variables and then print . Anyway try below code:
public static void main(String[] args) {
String s = "hello+pLus-minuss*multi/divide";
String[] ss = s.split("[-+*/]");
String first =ss[1];
String second =ss[2];
String third =ss[3];
String forth =ss[4];
System.out.println(first+"\n"+second+"\n"+third+"\n"+forth+"\n");
}
Output:
pLus
minuss
multi
divide
Try this out :
String data = "23+43*435/675-23";
Pattern pattern = Pattern.compile("[^\\+\\*\\/\\-]+");
Matcher matcher = pattern.matcher(data);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group());
}
for (int index = 0; index < list.size(); index++) {
System.out.println(index + " : " + list.get(index));
}
Output :
0 : 23
1 : 43
2 : 435
3 : 675
4 : 23
I think it is only the issue of index. You should have used index 0 to get the split result.
String[] split = s.split("\\+");
String[] split1 = split .split("\\-");
String[] split2 = split1 .split("\\*");
String[] split3 = split2 .split("\\/");
String hello= split[0];//split[0]=hello,split[1]=pLus-minuss*multi/divide
String plus= split1[0];//split1[0]=plus,split1[1]=minuss*multi/divide
String minus= split2[0];//split2[0]=minuss,split2[1]=multi/divide
String multi= split3[0];//split3[0]=multi,split3[1]=divide
String div= split3[1];
If the order of operators matters, change your code to this:
String s = "hello+pLus-minuss*multi/divide";
String[] split = s.split("\\+");
String[] split1 = split[1].split("\\-");
String[] split2 = split1[1].split("\\*");
String[] split3 = split2[1].split("\\/");
String plus = split1[0];
String minus = split2[0];
String multi = split3[0];
String div = split3[1];
System.out.println(plus + "\n" + minus + "\n" + multi + "\n" + div + "\n");
Otherwise, to spit on any operator, and store to variable do this:
public static void main(String[] args) {
String s = "hello+pLus-minuss*multi/divide";
String[] ss = s.split("[-+*/]");
String plus = ss[1];
String minus = ss[2];
String multi = ss[3];
String div = ss[4];
System.out.println(plus + "\n" + minus + "\n" + multi + "\n" + div + "\n");
}

Categories

Resources