Remove Substring from the Original String [duplicate] - java

This question already has answers here:
How can I remove a substring from a given String?
(14 answers)
Closed 3 years ago.
I am attempting to remove a substring from the original string
code attempted:
String details = events.event_details.value[bi];
String details2 ="";
if(details.length()>70) {
details2 = details.substring(70);
details.replaceFirst(details2, " ");
}

You do not remove it, you overwrite it with spaces...
remove is: cut it off!
replace: replace it!
details2 = details.substring(61, 70);
this gives you 10 chars
details2 = details.substring(details.length-10, details.length);
last 10
if you want 60 spaces and then the last 10, you need to create a String with 60 spaces, and use above method to extract whatever you want
maybe use a StringBuffer for this...
StringBuffer strg = new StringBuffer();
String cut = details.substring(details.length-10, details.length);
IntStream.iterate(0, i -> i++).limit(60).forEach((a) -> strg.append(" "));
strg.append(cut);
System.out.println(strg.toString());

You have to save your result from replaceFirst(...) somewhere,
as example again in details:
details = details.replaceFirst(details2, "");

You can try this way-
String details2 ="";
String result = ""
if(details.length()>70) {
details2 = details.substring(70);
result = details.replaceFirst(details2, " ");
}
System.out.println(result);
Here need a String variable where contain that replace's result

Related

Split the get the value using java [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 4 years ago.
I have a reply message in a String and I want to split it to extract a value.
My String reply message format is:
REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE,...);
My requirement is to get the value ABC024049364194 from the above string format.
I tried using this code, but it hasn't worked:
String[] arrOfStr = str.split(",", 5);
for (String a : arrOfStr)
System.out.println(a);
If you split the String, you will simply need to access the token at index 2.
// <TYPE>(<ARGUMENTS>)
String message = "REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE);";
Matcher m = Pattern.compile("(\\w+)\\((.+)\\)").matcher(message);
if (m.find()) {
String type = m.group(1);
String[] arguments = m.group(2).split(",");
System.out.println(type + " = " + arguments[2]); // REPLY = ABC024049364194
}
public static void main(String[] args) {
String str = "REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE,...)";
String code = str.split(",")[2];
System.out.println(code);
}
Will work if your code is always after 2 coma

Length of String within tags in java

We need to find the length of the tag names within the tags in java
{Student}{Subject}{Marks}100{/Marks}{/Subject}{/Student}
so the length of Student tag is 7 and that of subject tag is 7 and that of marks is 5.
I am trying to split the tags and then find the length of each string within the tag.
But the code I am trying gives me only the first tag name and not others.
Can you please help me on this?
I am very new to java. Please let me know if this is a very silly question.
Code part:
System.out.println(
getParenthesesContent("{Student}{Subject}{Marks}100{/Marks}{/Subject}{/Student}"));
public static String getParenthesesContent(String str) {
return str.substring(str.indexOf('{')+1,str.indexOf('}'));
}
You can use Patterns with this regex \\{(\[a-zA-Z\]*)\\} :
String text = "{Student}{Subject}{Marks}100{/Marks}{/Subject}{/Student}";
Matcher matcher = Pattern.compile("\\{([a-zA-Z]*)\\}").matcher(text);
while (matcher.find()) {
System.out.println(
String.format(
"tag name = %s, Length = %d ",
matcher.group(1),
matcher.group(1).length()
)
);
}
Outputs
tag name = Student, Length = 7
tag name = Subject, Length = 7
tag name = Marks, Length = 5
You might want to give a try to another regex:
String s = "{Abc}{Defg}100{Hij}100{/Klmopr}{/Stuvw}"; // just a sample String
Pattern p = Pattern.compile("\\{\\W*(\\w++)\\W*\\}");
Matcher m = p.matcher(s);
while(m.find()) {
System.out.println(m.group(1) + ", length: " + m.group(1).length());
}
Output you get:
Abc, length: 3
Defg, length: 4
Hij, length: 3
Klmopr, length: 6
Stuvw, length: 5
If you need to use charAt() to walk over the input String, you might want to consider using something like this (I made some explanations in the comments to the code):
String s = "{Student}{Subject}{Marks}100{/Marks}{/Subject}{/Student}";
ArrayList<String> tags = new ArrayList<>();
for(int i = 0; i < s.length(); i++) {
StringBuilder sb = new StringBuilder(); // Use StringBuilder and its append() method to append Strings (it's more efficient than "+=") String appended = ""; // This String will be appended when correct tag is found
if(s.charAt(i) == '{') { // If start of tag is found...
while(!(Character.isLetter(s.charAt(i)))) { // Skip characters that are not letters
i++;
}
while(Character.isLetter(s.charAt(i))) { // Append String with letters that are found
sb.append(s.charAt(i));
i++;
}
if(!(tags.contains(sb.toString()))) { // Add final String to ArrayList only if it not contained here yet
tags.add(sb.toString());
}
}
}
for(String tag : tags) { // Printing Strings contained in ArrayList and their length
System.out.println(tag + ", length: " + tag.length());
}
Output you get:
Student, length: 7
Subject, length: 7
Marks, length: 5
yes use regular expression, find the pattern and apply that.

How to split a specific string after in java [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 5 years ago.
I have the following string:
String result = "#sequence#A:exampleA#B:exampleB";
I would like to split this string into two strings like this:
String resulta = "sequence";
String resultb = "#A:exampleA#B:exampleB";
How can I do this? I'm new to Java programming language.
Thanks!
if you want typical split, (Specific to your string), you can call substring and get the part of it like below:
String s = "#sequence#A:exampleA#B:exampleB";
String s1= s.substring(1,s.indexOf("#",1));
System.out.println(s1);
String s2= s.substring(s1.length()+1);
System.out.println(s2);
}
Edit as per your comment
String s3= s.substring(s.indexOf("#",1));
System.out.println(s3);
Try,
String result = "#sequence#A:exampleA#B:exampleB", resulta, resultb;
int splitPoint = result.indexOf('#',1);
resulta = result.substring(1, splitPoint);
resultb = result.substring(splitPoint);
System.out.println(resulta+", "+resultb);
String result = "#sequence#A:exampleA#B:exampleB";
if(result.indexOf("#") == 0)
result = result.substring(1, result.length());
String resultA = result.substring(0, result.indexOf("#"));
String resultB = result.substring(resultA.length(), result.length());

How to split a string with value contains the delimiter also in java? [duplicate]

This question already has answers here:
Java: splitting a comma-separated string but ignoring commas in quotes
(12 answers)
Closed 5 years ago.
I have a string with value - String sData = "abc|def|\"de|er\"|123"; and I will need to split it with delimiter - "|". In this case, my expected result will be
abc
def
"de|er"
123
Below is my code
String sData = "abc|def|\"de|er\"|123";
String[] aSplit = sData.split(sDelimiter);
for(String s : aSplit) {
System.out.println(s);
}
But it actually comes out the below result
abc
def
"de
er"
123
I have tried with this pattern - String sData = "abc|def|\"de\\|er\"|123"; but it's still not returning my expected result.
Any idea how can I achieve my expected result?
This worked for me:
String sData = "abc|def|\"de|er\"|123";
String[] aSplit = sData.split("\\|");
for(int i = 0; i < aSplit.length; i++) {
if(aSplit[i].startsWith("\"")) {
if(aSplit[i+1].endsWith("\"")) {
aSplit[i] = aSplit[i] + "|" + aSplit[i+1];
aSplit[i+1] = "";
}
}
}
for(String s : aSplit) {
if(!s.equals(""))
System.out.println(s);
}
The output:
abc
def
"de|er"
123

Split String Having delimeter, but I need the delimeter at some places [duplicate]

This question already has answers here:
Currency values string split by comma
(3 answers)
Closed 7 years ago.
I need to split the string which contains amount like "1,000.00,106,924.31" . how to do this??
Peviously I have tried using split by ',' but it is giving me output as 1,000.00,106,924.31.
But i need output as 1,000.00 106,924.31.
You can something like this:
public static void main(String[] args) {
String amounts = "1,000.00,106,924.31";
List<String> results = new ArrayList<>();
do {
int indexOfFirstComma = amounts.indexOf(",");
String sub_amounts = amounts.substring(indexOfFirstComma+1);
String splitComma = sub_amounts.split(",")[0];
results.add(amounts.substring(0, indexOfFirstComma) + "," + splitComma);
if (sub_amounts.indexOf(",")>0) {
amounts = sub_amounts.substring(sub_amounts.indexOf(",")+1);
}else {
break;
}
}while (true);
results.forEach(System.out::println);
}

Categories