Is it possible to check if a substring contains a certain value and do something? I have this piece of code i'm wondering if I could check if desc: contains the value \n I have the config made with the following information
test: desc:\ndog\ntest
test2: desc:\ndog3
So how would I be able to retrieve the \n and loop through all the \n in that specific string list and do a action.
for (String s : plugin.file.getFile().getStringList(plugin.file.path))
{
public void substring(){
String labels = "item: desc:";
String[] parts = labels.split(" ");
String part1 = parts[0];
String part2 = parts[1];
System.out.println("Desc Value: " + s.substring(part2.length()).split(" ")[1])
}
}
I don't understand your question in full but I think that you want something like this:
String test = "desc:\ndog\ntest";
String test1 = "desc:\ndog3";
String[] parts = test.split(":");
String name = parts[0];
String[] values = parts[1].trim().split("\n");
System.out.println("Name: " + name);
for (int i = 0; i<values.length; i++)
{
System.out.println(values[i]);
}
You just split the values of [1] index in that parts table.
Related
I have a string as:
"model=iPhone12,3,os_version=13.6.1,os_update_exist=1,status=1"
How can I convert this into:
model=iPhone12,3
os_version=13.6.1
os_update_exist=1
status=1
Split the string from the first comma, then re-join the first two elements of the resulting string array.
I doubt there's a "clean" way to do this but this would work for your case:
String str = "model=iPhone12,3,os_version=13.6.1,os_update_exist=1,status=1";
String[] sp = str.split(",");
sp[0] += "," + sp[1];
sp[1] = sp[2];
sp[2] = sp[3];
sp[3] = sp[4];
sp[4] = "";
You can try this:
public String[] splitString(String source) {
// Split the source string based on a comma followed by letters and numbers.
// Basically "model=iPhone12,3,os_version=13.6.1,os_update_exist=1,status=1" will be split
// like this:
// model=iPhone12,3
// ,os_version=13.6.1
// ,os_update_exist=1
// ,status=1"
String[] result = source.split("(?=,[a-z]+\\d*)");
for (int i = 0; i < result.length; i++) {
// Removes the comma at the beginning of the string if present
if (result[i].matches(",.*")) {
result[i] = result[i].substring(1);
}
}
return result;
}
if you are parsing always the same kind of String a regex like this will be do the job
String str = "model=iPhone12,3,os_version=13.6.1,os_update_exist=1,status=1";
Matcher m = Pattern.compile("model=(.*),os_version=(.*),os_update_exist=(.*),status=(.*)").matcher(str);
if (m.find()) {
model = m.group(1)); // iPhone12,3
os = m.group(2)); // 13.6.1
update = m.group(3)); // 1
status = m.group(4)); // 1
}
If you really wants to use a split you can still use that kind of trick
String[] split = str.replaceAll(".*?=(.*?)(,[a-z]|$)", "$1#")
.split("#");
split[0] // iPhone12,3
split[1] // 13.6.1
split[2] // 1
split[3] // 1
I have a string like this: "aa-bb,ccdd,eeff,gg-gg,cc-gg". I need to split the string by '-' signs and create two strings from it, but if the comma-delimited part of the original string doesn't contain '-', some placeholder character needs to be used instead of substring. In case of above example output should be:
String 1:
"{aa,ccdd,eeff,gg,cc}"
String 2:
"{bb,0,0,gg,gg}"
I can't use the lastIndexOf() method because input is in one string. I am not sure how to much the parts.
if(rawIndication.contains("-")){
String[] parts = rawIndication.split("-");
String part1 = parts[0];
String part2 = parts[1];
}
Here is a Java 8 solution, using streams. The logic is to first split the input string on comma, generating an array of terms. Then, for each term, we split again on dash, retaining the first entry. In the case of a term having no dashes, the entire string would just be retained. Finally, we concatenate back into an output string.
String input = "aa-bb,ccdd,eeff,gg-gg,cc-gg";
int pos = 1;
String output = String.join(",", Arrays.stream(parts)
.map(e -> e.split("-").length >= (pos+1) ? e.split("-")[pos] : "0")
.toArray(String[]::new));
System.out.println(output);
This outputs:
bb,0,0,gg,gg
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
// First split the source String by comma to separate main parts
String[] mainParts = sourceStr.split(",");
for (String mainPart: mainParts) {
// Check if each part contains '-' character
if (mainPart.contains("-")) {
// If contains '-', split and add the 2 parts to 2 arrays
String[] subParts = mainPart.split("-");
list1.add(subParts[0]);
list2.add(subParts[1]);
} else {
// If does not contain '-', add complete part to 1st array and add placeholder to 2nd array
list1.add(mainPart);
list2.add("0");
}
}
// Build the final Strings by joining String parts by commas and enclosing between parentheses
String str1 = "{" + String.join(",", list1) + "}";
String str2 = "{" + String.join(",", list2) + "}";
System.out.println(str1);
System.out.println(str2);
With the way you structured the problem, you should actually be splitting by commas first. Then, you should iterate through the result of the call to split and split each string in the outputted array by hyphen if there exists one. If there isn't a hyphen, then you can add a 0 to string 2 and the string itself to string 1. If there is a hyphen, then add the left side to string 1 and the right side to string 2. Here's one way you can do this,
if(rawIndication.contains(",")){
String s1 = "{";
String s2 = "{";
String[] parts = rawIndication.split(",");
for(int i = 0; i < parts.length; i++) {
if(parts[i].contains("-") {
String[] moreParts = parts[i].split(",");
s1 = s1 + moreParts[0] + ",";
s2 = s2 + moreParts[1] + ",";
}
else{
s1 = s1 + parts[i] + ",";
s2 = "0,";
}
}
s1 = s1.substring(0, s1.length() - 1); //remove last extra comma
s2 = s2.substring(0, s2.length() - 1); //remove last extra comma
s1 = s1 + "}";
s2 = s2 + "}";
}
I think this solves your problem.
private static void splitStrings() {
List<String> list = Arrays.asList("aa-bb", "ccdd", "eeff", "gg-gg", "cc-gg");
List firstPartList = new ArrayList<>();
List secondPartList = new ArrayList<>();
for (String undividedString : list){
if(undividedString.contains("-")){
String[] dividedParts = undividedString.split("-");
String firstPart = dividedParts[0];
String secondPart = dividedParts[1];
firstPartList.add(firstPart);
secondPartList.add(secondPart);
} else{
firstPartList.add(undividedString);
secondPartList.add("0");
}
}
System.out.println(firstPartList);
System.out.println(secondPartList);
}
Output is -
[aa, ccdd, eeff, gg, cc]
[bb, 0, 0, gg, gg]
so first here is my code :
public class eol {
public static void main(String[] args) {
String x = "Charles.Baudelaire*05051988*France Sergei.Esenin*01011968*Russia Herman.Hesse*23051996*Germany";
String[] word= x.split("[.,*, ]");
for(int i=0;i<word.length;i++){
// System.out.print(word[i]+" ");
}
String name = word[0];
String lastname = word[1];
String dod =word[2];
String cob= word[3];
System.out.print("First person data : "+
"\n"+ name +" "+ "\n"+lastname+" "+"\n"+ dod+" "+"\n"+ cob);
I want to loop through string x, and take needed values, and use them to make 3 objects of class writer, is there any way i do this with for loop ?
Or would i have to "break" original string in 3 smaller arrays, then do for loop for every one of them.
I mean, i can use for loop to print out data on screen, by incrementing counter by certain value, how ever to add these data to fields is something I don't understand how to do.
Sure. You can do the following:
Validate.isTrue(word.length % 4 == 0, "Array size must be a multiple of 4");
List<Writer> writers = new ArrayList<>();
for (int i=0; i<word.length; i+=4) {
String name = word[i];
String lastname = word[i+1];
String dod =word[i+2];
String cob= word[i+3];
writers.add(new Writer(name, lastname, dod, cob));
}
i += 4 instead of i++ after each tern of loop, and use word[i], word[i+1], word[i+2] and word[i+3] in loop.
i.e.
String x = "Charles.Baudelaire*05051988*France Sergei.Esenin*01011968*Russia Herman.Hesse*23051996*Germany";
String[] word= x.split("[.,*, ]");
for(int i=0;i<word.length;i+=4){
String name = word[i];
String lastname = word[i+1];
String dod =word[i+2];
String cob= word[i+3];
// Use these variable.
}
I cannot figure out how to change the order of a given name.
For example: Van-Dame Claud
Result: Claud Dame-Van
I created this method, but it seems that is not correct, any suggestion or maybe a better method?
public String NameInvers(){
String Name, Name = null, Name = null, NameFinal;
int s1 = getName().indexOf(' ');
int s2 = getName().indexOf('-');
if(s1 != 0){
Name1 = getName().substring(0, s1);
if(s2 != 0)
{
Name2 = getName().substring(s1, s2);
Name3 = getName().substring(s2);
}
NameFinal = Name3 + Name2 + Name1;
}
else
NameFinal = getName();
return NameFinal;
}
Edit: In my Main method I have a number of names. The thing is that it says: throw new StringIndexOutOfBoundsException(subLen) and it won't show up.
Here you go:
public static String reverseName (String name) {
name = name.trim();
StringBuilder reversedNameBuilder = new StringBuilder();
StringBuilder subNameBuilder = new StringBuilder();
for (int i = 0; i < name.length(); i++) {
char currentChar = name.charAt(i);
if (currentChar != ' ' && currentChar != '-') {
subNameBuilder.append(currentChar);
} else {
reversedNameBuilder.insert(0, currentChar + subNameBuilder.toString());
subNameBuilder.setLength(0);
}
}
return reversedNameBuilder.insert(0, subNameBuilder.toString()).toString();
}
Test:
public static void main(String[] args) {
printTest("Van-Dame Claud");
printTest("Victor Hugo");
printTest("Anna");
printTest("");
}
private static void printTest(String S) {
System.out.printf("Reverse name for %s: %s\n", S, reverseName(S));
}
Output:
Reverse name for Van-Dame Claud: Claud Dame-Van
Reverse name for Victor Hugo: Hugo Victor
Reverse name for Anna: Anna
Reverse name for :
First of all, you duplicate your variable Name declaration, three times. I suppose that you want to put:
String Name1, Name2 = null, Name3 = null, NameFinal;
instead of:
String Name, Name = null, Name = null, NameFinal;
Then, if you just have 2 names with a - in the middle and you want to change their order you can use split function to separate it, finding where - is. You can use it like this:
String string = "Van-Dame Claud";
String[] divide = string.split("-");
String Name1 = divide[0];
String Name2 = divide[1];
String result = Name2 + "-" + Name1;
EDIT: Name1 will be Van and Name2 will be Dame Claud so the result will be Dame Cloud-Van.
I expect it works for you!
You want to have a method to convert all names or just the the names in form of Name-Name Name? I'm assuming you want a method for all names. Since if you just want to reverse names in this specific form, there is no meaning for you to check value of s1 and s2, you know s1 and s2 must be a positive number. If you check because you want to do error checking, then you should throw an exception if the name is not in the form you want. If you want to do it for all names, below is the pseudocode, you can implement it yourself (your code contains several errors, you are using Name1, Name2, Name3, but you never declared them and duplicate variable Name declaration):
string finalName = ""
string [] strs1 = name split by " "
foreach str1 in strs1
string [] strs2 = str1 split by "-"
foreach str2 in strs2
if str2.first?
finalName = str2 + " " + finalName
else
finalName = str2 + "-" + finalName
end
end
end
return finalName.substring 0, finalName.length-1 //remove the space at the end
I think this would work. Hope you find it useful.
String str = "AlwinX-road-9:00pm-kanchana travels-25365445421";
String[] names = str.split("-");
I want output like following:
AlwinX-road
9:00pm
kanchana travels
25365445421
Use pattern matching to match your requirement
String str = "AlwinX-road-9:00pm-kanchana travels-25365445421";
String regex = "(^[A-Z-a-z ]+)[-]+(\\d+:\\d+pm)[-]([a-z]+\\s+[a-z]+)[-](\\d+)";
Matcher matcher = Pattern.compile( regex ).matcher( str);
while (matcher.find( ))
{
String roadname = matcher.group(1);
String time = matcher.group(2);
String travels = matcher.group(3);
String digits= matcher.group(4);
System.out.println("time="+time);
System.out.println("travels="+travels);
System.out.println("digits="+digits);
}
Since you want to include the delimiter in your first output line, you can do the split, and merge the first two element with a -: -
String[] names = str.split("-");
System.out.println(names[0] + "-" + names[1])
for (int i = 2;i < names.length; i++) {
System.out.println(names[i])
}
The split() method can't distinguish the dash in AlwinX-road and the other dashes in the string, it treats all the dashes the same. You will need to do some sort of post processing on the resulting array. If you will always need the first two strings in the array joined you can just do that. If your strings are more complex you will need to add additional logic to join the strings in the array.
One way you could do it, assuming the first '-' is always part of a two part identifier.
String str = "AlwinX-road-9:00pm-kanchana travels-25365445421";
String[] tokens = str.split("-");
String[] output = new String[tokens.length - 1];
output[0] = tokens[0] + '-' + tokens[1];
System.out.println(output[0]);
for(int i = 1; i < output.length; i++){
output[i] = tokens[i+1];
System.out.println(output[i]);
}
Looks like you want to split (with removal of all dashes but the first one).
String str = "AlwinX-road-9:00pm-kanchana travels-25365445421";
String[] names = str.split("-");
for (String value : names)
{
System.out.println(value);
}
So its produces:
AlwinX
road
9:00pm
kanchana travels
25365445421
Notice that "AlwinX" and "road" we split as well since they had a dash in between. So you will need custom logic to handle this case. here is an example how to do it (I used StringTokenizer):
StringTokenizer tk = new StringTokenizer(str, "-", true);
String firstString = null;
String secondString = null;
while (tk.hasMoreTokens())
{
final String token = tk.nextToken();
if (firstString == null)
{
firstString = token;
continue;
}
if (secondString == null && firstString != null && !token.equals("-"))
{
secondString = token;
System.out.println(firstString + "-" + secondString);
continue;
}
if (!token.equals("-"))
{
System.out.println(token);
}
}
This will produce:
AlwinX-road
9:00pm
kanchana travels
25365445421
from your format, I think you want to split the first one just before the time part. You can do it this way:
String str =yourString;
String beforetime=str.split("-\\d+:\\d+[ap]m")[0]; //this is your first token,
//AlwinX-road in your example
String rest=str.substring(beforetime.length()+1);
String[] restNames=rest.split("-");
If you really need it all together in one array then see the code below:
String[] allTogether=new String[restNames.length+1];//the string with all your tokens
allTogether[0]=beforetime;
System.arraycopy(restNames, 0, allTogether, 1, restNames.length);
If you use "_" as a separator instead of "-": AlwinX-road_9:00pm_kanchana travels_25365445421
New code:
String str = new String("AlwinX-road_9:00pm_kanchana travels_25365445421");
String separator = new String("_");
String[] names = str.split(separator);
for(int i=0; i<names.length; i++){
System.out.println(names[i]);
}