Joining two strings with delimiters - java

I'm trying to join two strings together that have comma delimiters. I want to loop it so that it becomes consecutive, meaning that the first item in string one before the comma is then followed by the first item in string two and so on. Here is the two strings and how I would want them to join.
String 1 = 0,E,EEE,0,0,WWWW,EE,W,EE
String 2 = 0,NNN,N,SS,0,S,N,N,SS
Outcome = 00,ENNN,EEEN,0SS,00,WWWS,EEN,WN,EESS
Is this even possible? I have the code to join the two strings but it doesn't put them in the order I'm needing.

Split one and two by , and then use IntStream to generate the indices of your two token arrays and join the elements by concatenation and then ,. Like,
String a = "0,E,EEE,0,0,WWWW,EE,W,EE", b = "0,NNN,N,SS,0,S,N,N,SS";
String[] aTok = a.split(","), bTok = b.split(",");
String out = IntStream.range(0, Math.min(aTok.length, bTok.length))
.mapToObj(i -> aTok[i] + bTok[i]).collect(Collectors.joining(","));
System.out.println(out);
Outputs (as requested)
00,ENNN,EEEN,0SS,00,WWWWS,EEN,WN,EESS

Split each string into a string array,
concatenate the items of the same index in both tables and append a , after each pair:
String s1 = "0,E,EEE,0,0,WWWW,EE,W,EE";
String s2 = "0,NNN,N,SS,0,S,N,N,SS";
String[] tokens1 = s1.split(",");
String[] tokens2 = s2.split(",");
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < tokens1.length; i++) {
sb.append(tokens1[i]).append(tokens2[i]).append(",");
}
sb.deleteCharAt(sb.length() - 1); // remove the last ","
String result = sb.toString();
System.out.println(result);
Of course this works only if the 2 strings can be split in the same number of items.

Related

Java: How to split a String into two separate arrays after a space? [duplicate]

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));

Converting a string[] into a string then split into an array

I need help creating a loop which splits strings. So far I have the code below.
System.out.println("*FILE HAS BEEN LOCATED*");
System.out.println("*File contains: \n");
List<String> lines = new ArrayList<String>();
while (scan.hasNextLine())
{
lines.add(scan.nextLine());
}
String[] arr = lines.toArray(new String[0]);
String str_array = Arrays.toString(arr);
String[] arraysplit;
arraysplit = str_array.split(":");
for (int i=0; i<arraysplit.length; i++)
{
arraysplit[i] = arr[i].trim();
System.out.println(arr[i]);
}
an example of one of the strings would be
Firstname : Lastname : age
I want it to split the string into another array that looks like:
Firstname
Lastname
age
I still encounter an error when running the code, it seems as though when I convert the array to a string, it puts commas in the string and therefore it causes problems as I'm trying to split the string on : not ,
image:
Issue : you are using the old array arr to display values and arraysplit will have resultant values of split method so you need to apply trim() on arraysplit's elements and assign back the elements to same indexes
String[] arraysplit;
arraysplit = str_array.split(":");
for (int i=0; i<arraysplit.length; i++)
{
arraysplit[i] = arraysplit[i].trim();
// ^^^^^^^^^^^^ has values with spaces
System.out.println(arr[i]);
}
System.out.println(arraysplit[i]);
To simplify solution without (list to array and array to string complication)
1.) Create array of length as sizeOfList * 3
2.) split the list element using \\s*:\\s*
3.) Use array copy with jas index of resultant array to keep the track of the array index
String result[] = new String [lines.size()*3];
int j=0;
for (int i=0; i<lines.size(); i++)
{
System.arraycopy(lines.get(0).split("\\s*:\\s*"), 0, result, j, 3);
j+=3;
}
System.out.println(Arrays.toString(result));
You can use regex str_array.split("\\s*:\\s*"); where
\\s*:\\s* : \\s* mean zero or more spaces then : character then zero or more spaces
arraysplit = str_array.split("\\s*:\\s*");
// just use values of arraysplit
Split using this regex \s*:\s*
String[] arraysplit = str_array.split("\\s*:\\s*");
details :
\s* zero or more spaces
followed by lateral character :
followed by \s* zero or more spaces
regex demo

Replace specific character and getting index in Java

I have tried a code to replace only specific character. In the string there are three same characters, and I want to replace the second or third character only. For example:
String line = "this.a[i] = i";
In this string there are three 'i' characters. I want to replace the second or third character only. So, the string will be
String line = "this.a[i] = "newChar";
This is my code to read the string and replace it by another string:
String EQ_VAR;
EQ_VAR = getequals(line);
int length = EQ_VAR.length();
if(length == 1){
int gindex = EQ_VAR.indexOf(EQ_VAR);
StringBuilder nsb = new StringBuilder(line);
nsb.replace(gindex, gindex, "New String");
}
The method to get the character:
String getequals(String str){
int startIdx = str.indexOf("=");
int endIdx = str.indexOf(";");
String content = str.substring(startIdx + 1, endIdx);
return content;
}
I just assume that using an index is the best option to replace a specific character. I have tried using String replace but then all 'i' characters are replaced and the result string look like this:
String line = "th'newChar's.a[newChar] = newChar";
Here's one way you could accomplish replacing all occurances except first few:
String str = "This is a text containing many i many iiii = i";
String replacement = "hua";
String toReplace = str.substring(str.indexOf("=")+1, str.length()).trim(); // Yup, gets stuff after "=".
int charsToNotReplace = 1; // Will ignore these number of chars counting from start of string
// First replace all the parts
str = str.replaceAll(toReplace, replacement);
// Then replace "charsToNotReplace" number of occurrences back with original chars.
for(int i = 0; i < charsToNotReplace; i++)
str = str.replaceFirst(replacement, toReplace);
// Just trim from "="
str = str.substring(0, str.indexOf("=")-1);
System.out.println(str);
Result: This huas a text contahuanhuang many hua many huahuahuahua;
You set set charsToNotReplace to however number of first number of chars you want to ignore. For example setting it to 2 will ignore replacing first two occurrences (well, technically).

Splitting query string using multiple delimiters - java

I would like to split these strings:
/d/{?a}
/a/b/{c}{?d}
/a/b/c{?d}
into following list of segments:
[d, {?a}] (this case is easy, just split using /)
[a, b, {c}, {?d}]
[a, b, c, {?d}]
For the other cases, splitting using / will not get the result that I wanted. In which case, the last string element of 2. and 3. will be {c}{?d} and c{?d}.
What is the best approach to achieve all 1,2,3 at the same time?
Thanks.
try to solve the problem with a regex. This might be a script to start with:
String regex = "(/)|(?=\\{)";
String s = "/a/b/{c}{?d}";
String[] split = s.split(regex);
you will get empty elements in the split array with this regex, but all other elements are splitted correctly
Here is some simple way of solving it in case you know your input is always going to be either any chars xyz different than { and } or {xyz}. In case you could have any other input, this would require some modifications:
String[] arr = input.split("/");
List<String> result = new ArrayList<>();
for (String elem : arr) {
int lastCut = 0;
for (int i = 0; i < elem.length(); i++) {
if (elem.charAt(i) == '{' || elem.charAt(i) == '}') {
if (i > 0) {
String previousElem = elem.substring(lastCut, i);
result.add(previousElem);
}
lastCut = i;
}
}
if (lastCut < elem.length() - 2)
String lastElem = elem.substring(lastCut + 1, elem.length());
result.add(lastElem);
}
In the first case it's splitting. But in the rest cases it's parsing.
You have to parse a string first and then split it. Try to add '/' right before every '{' and after every '}'. And then you can split it by '/'.
E.g.:
Before parsing:
2. /a/b/{c}{?d}
3. /a/b/c{?d}
After parsing:
2. /a/b//{c}//{?d}/
3. /a/b/c/{?d}/
Then remove excessive '/', split the string and be happy.

How can I parse a "key1:value1, value, key2:value3" string into ArrayLists?

I have a string
String line = "abc:xyz uvw, def:ghi, mno:rst, ijk:efg, abc opq";
I want to parse this string into two lists:
ArrayList<String> tags;
ArrayList<String> values;
where the tags are the words before the colon (in my example: abc, def, ijk and mno). That is I want
tags = Arrays.asList("abc", "def", "mno", "ijk");
values = Arrays.asList("xyz uvw", "ghi", "rst", "efg, abc opq");
Note that the values can have spaces and commas in them and are not just one word.
Since your values can contain commas, you need to split when you find a key.
A key is defined as a word preceding a :.
So, your split pattern will be ", (?=[a-zA-z]+:)"
This checks for a comma space chars colon in the specified order, looking ahead the chars and colon.
Checks for a key, and splits with lookahead (thus leaving the key intact). This will give you an array of keyValue pairs
Then you can split with : to get the keys and values.
String str = "Your string";
String[] keyValuePairs = str.split(", (?=[a-zA-z]+:)");
for (String keyValuePair : keyValuePairs) {
String[] keyvalue = keyValuePair.split(":");
keysArray.add(keyvalue[0]);
valuesArray.add(keyvalue[1]);
}
I would go with a regex. I am not sure how to do this in Java but in python that would be:
(\w+):([ ,\w]+)(,|$)
Tested on pythex with input abc:xy z uvw, def:g,hi, mno:rst. The result is:
Match 1
1. abc
2. xy z uvw
3. ,
Match 2
1. def
2. g,hi
3. ,
Match 3
1. mno
2. rst
3. Empty
So for each match you get the key in position 1 and the value in 2. The separator is stored in 3
First obtain your string from the file
List<String> tags = new ArrayList<String>();
List<String> values = new ArrayList<String>;
String lineThatWasRead = ...
Then we split it by commas to obtain the pairs, and for each pari split by :
List<String> separatedStringList = Arrays.asList(lineThatWasRead.split(","));
for (String str : separatedStringList)
{
//Since it is possible values also contain commas, we have to check
//if the current string is a new pair of tag:value or just adding to the previous value
if (!str.contains(":"))
{
if (values.size > 0)
{
values.set(values.size() - 1, values.get(values.size()-1) + ", " + str);
continue; //And go to next str since this one will not have new keys
}
}
String[] keyValArray = str.split(:);
String key = keyValArray[0];
String val = keyValArray[1];
tags.add(key);
values.add(val);
}
Note that you are not forced to use a list but I just like the flexibility they give. Some might argue String[] would perform better for the first split by ,.
You get your line as string.
//your code here
String line = //your code here
String[] stuff = line.split(":")// this will split your line by ":" symbol.
stuff[0] //this is your key
stuff[1] //this is your value

Categories