How to trim the last characters from a arrays in Java - java

I have an Array of 10 strings:
so now when i get the InnerText from the object,
i want to trim off the last characters of all the strings within the Array
I have -->
println(Array)
Array =
[User RolesPDF, Create New UserPDFVideo, Create Self-Registration CodePDF, User ManagementPDF, Email SettingsPDF, Download RFIsPDF, Manage Departments & Setup HierarchiesPDFVideo, Tracer Category SetupPDFVideo, Guest Access SetupPDF]
I want to get rid of the PDF (3 characters so the pDF at the end is removed)
Also - Video (8 characters removed)
def Array = []
WebUI.comment('Top of Page - For loop for all Text of pdf and videos, and also clicking on all PDFs')
for (i = 1; i < 10; i++) {
WebUI.delay(1)
WebUI.scrollToPosition(80, 80)
String innertext = driver.findElement(By.xpath(('//div[#class=\'content-sections\']/div[1]//div[#class=\'col-12 col-xl-6\']/div[' +
i) + ']//div[#class=\'item\']')).getText()
println(innertext)
Array << innertext
I have tried:
def Arraysliced =Array.size
for (int i = 0;i<Array.size;i++){
Arraysliced[i].substring(0)
println(Arraysliced);
}
String delims = "[ ]+";
String Arraysliced = Array.split(delims)
Arraysliced = Array
def Arraysliced = []
Arraysliced = Array.split('-'[0])
(Array.split('-')[0])
println(Arraysliced)

Can you try below code-
String [] arrsplit = innertext.split("//PDF");
and use arrsplit[0] to add in your code
> **Output would be**- if innertext is- Create New UserPDFVideo
> arrsplit[0]=Create New User arrsplit[1]=Video //which you need to ignore.

Related

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.

I am not able to make regex for the following String [duplicate]

I have a string like this:
"core/pages/viewemployee.jsff"
From this code, I need to get "viewemployee". How do I get this using Java?
Suppose that you have that string saved in a variable named myString.
String myString = "core/pages/viewemployee.jsff";
String newString = myString.substring(myString.lastIndexOf("/")+1, myString.indexOf("."));
But you need to make the same control before doing substring in this one, because if there aren't those characters you will get a "-1" from lastIndexOf(), or indexOf(), and it will break your substring invocation.
I suggest looking for the Javadoc documentation.
You can solve this with regex (given you only need a group of word characters between the last "/" and "."):
String str="core/pages/viewemployee.jsff";
str=str.replaceFirst(".*/(\\w+).*","$1");
System.out.println(str); //prints viewemployee
You can split the string first with "/" so that you can have each folder and the file name got separated. For this example, you will have "core", "pages" and "viewemployee.jsff". I assume you need the file name without the extension, so just apply same split action with "." seperator to the last token. You will have filename without extension.
String myStr = "core/pages/viewemployee.bak.jsff";
String[] tokens = myStr.split("/");
String[] fileNameTokens = tokens[tokens.length - 1].split("\\.");
String fileNameStr = "";
for(int i = 0; i < fileNameTokens.length - 1; i++) {
fileNameStr += fileNameTokens[i] + ".";
}
fileNameStr = fileNameStr.substring(0, fileNameStr.length() - 1);
System.out.print(fileNameStr) //--> "viewemployee.bak"
These are file paths. Consider using File.getName(), especially if you already have the File object:
File file = new File("core/pages/viewemployee.jsff");
String name = file.getName(); // --> "viewemployee.jsff"
And to remove the extension:
String res = name.split("\\.[^\\.]*$")[0]; // --> "viewemployee"
With this we can handle strings like "../viewemployee.2.jsff".
The regex matches the last dot, zero or more non-dots, and the end of the string. Then String.split() treats these as a delimiter, and ignores them. The array will always have one element, unless the original string is ..
The below will get you viewemployee.jsff:
int idx = fileName.replaceAll("\\", "/").lastIndexOf("/");
String fileNameWithExtn = idx >= 0 ? fileName.substring(idx + 1) : fileName;
To remove the file Extension and get only viewemployee, similarly:
idx = fileNameWithExtn.lastIndexOf(".");
String filename = idx >= 0 ? fileNameWithExtn.substring(0,idx) : fileNameWithExtn;

How could I split a String into an array in Kotlin?

I need to split a String read in from a file into an array of values. I want to split the String at the commas, so for example, if the String read:
"name, 2012, 2017"
The values in the array would be:
array index 0 - name
array index 1 - 2012
array index 2 - 2017
I found this example in Java:
String[] stringArray = string.split(",");
How I could do it in Kotlin?
val strs = "name, 2012, 2017".split(",").toTypedArray()
If we have a string of values that splited by any character like ",":
val values = "Name1 ,Name2, Name3" // Read List from somewhere
val lstValues: List<String> = values.split(",").map { it -> it.trim() }
lstValues.forEach { it ->
Log.i("Values", "value=$it")
//Do Something
}
It's better to use trim() to delete spaces around strings if exist.
Consider that if have a "," at the end of string it makes one null item, so can check it with this code before split :
if ( values.endsWith(",") )
values = values.substring(0, values.length - 1)
if you want to convert list to Array ,use this code:
var arr = lstValues.toTypedArray()
arr.forEach { Log.i("ArrayItem", " Array item=" + it ) }
Simple as it is:
val string: String = "leo_Ana_John"
val yourArray: List<String> = string.split("_")
you get: yourArray[0] == leo, yourArray[1] == Ana, yourArray[2]==John
In this case, just change the "_" from my code to ", " of yours. Se bellow
val yourArray: List<String> = string.split(", ")
var newStrg= "853 kB"
val mString = newStrg!!.split(" ").toTypedArray()
Here Split parameter is space
mString[0] = "853"
mString[1] = "kB"
Split a string using inbuilt split method then using method extensions isNum() to return numeric or not.
fun String.isNum(): Boolean{
var num:Int? = this.trim().toIntOrNull()
return if (num != null) true else false
}
for (x in "name, 2012, 2017".split(",")) {
println(x.isNum())
}
If you want to use multiple/several delimiters in kotlin split, you need to pass them separately:
val validUrl = "http://test.com/</a> -".split(">", " ", "<").first()

Java code to process special characters that need to be replaced by other special characters

I am writing Java code to process a string received from a Mainframe that contains special characters that need to be replaced by other special characters, my search characters are §ÄÖÜäüßö#[\]~{¦} and the replacement characters are #[\]{}~¦§ÄÖÜßäöü so if the string has a { in it I need to replace it with ä and example of my input is "0.201322.05.2017LM-R{der Dopp"
My code currently is
String repChar = "§ÄÖÜäüßö#[\\\\]~{¦}#[\\\\]{}~¦§ÄÖÜßäöü";
// Split String and Convert
String repCharin = repChar.substring(0, repChar.length()/2-1);
String repCharout = repChar.substring(repChar.length()/2, repChar.length()-1);
String strblob = new String(utf8ContentIn);
// Convert
for (int j=0; j < repCharin.length();j++) {
strblob = strblob.replace(repCharin.substring(j, 1), repCharout.substring(j, 1));
}
byte [] utf8Content = strblob.getBytes();
But it generates the following error
java.lang.StringIndexOutOfBoundsException at
java.lang.String.substring(String.java:1240)
The \\ are escaped characters I only need a single \
The code
String utf8ContentIn = "0.201322.05.2017LM-R{der Dopp";
String repChar = "§ÄÖÜäüßö#[\\]~{¦}#[\\]{}~¦§ÄÖÜßäöü";
// Split String and Convert
String repCharin = repChar.substring(0, repChar.length() / 2);
String repCharout = repChar.substring(repChar.length() / 2, repChar.length());
String strblob = new String(utf8ContentIn);
String output = strblob.chars().mapToObj(c -> {
char ch = (char) c;
int index = repCharin.indexOf(c);
if (index != -1) {
ch = repCharout.charAt(index);
}
return String.valueOf(ch);
}).collect(Collectors.joining());
System.out.println(output);
will print "0.201322.05.2017LM-Räder Dopp" as you expect. Your problem here (besides incorrect indexes during separation) is that you should iterate input string instead of your characters. Because you can run into situation when you replace Ä with [ and after threat [ as special character again and replace it second time with Ä.
Also, single backslash should be escaped with single backslash, so to get \ you need \\
Hope it helps!

how to remove anchor tag and make it text

String k= <html>
<a target="_blank" href="http://www.taxmann.com/directtaxlaws/fileopencontainer.aspx?Page=CIRNO&
amp;id=1999033000019320&path=/Notifications/DirectTaxLaws/HTMLFiles/S.O.193(E)30031999.htm&
amp;aa=">number S.O.I93(E), dated the 30th March, 1999
</html>
I'm getting this HTML in a String and I want to remove the anchor tag so that data is also removed from link.
I just want display it as text not as a link.
how to do this i m trying to do so much not able to do please send me code regarding that i m
creating app for Android this issue i m getting in android on web view.
use JSoup, and jSoup.parse()
You can use the following example (don't remember where i've found it, but it works) using replace method to modify the string before showing it:
k = replace ( k, "<a target=\"_blank\" href=", "");
String replace(String _text, String _searchStr, String _replacementStr) {
// String buffer to store str
StringBuffer sb = new StringBuffer();
// Search for search
int searchStringPos = _text.indexOf(_searchStr);
int startPos = 0;
int searchStringLength = _searchStr.length();
// Iterate to add string
while (searchStringPos != -1) {
sb.append(_text.substring(startPos, searchStringPos)).append(_replacementStr);
startPos = searchStringPos + searchStringLength;
searchStringPos = _text.indexOf(_searchStr, startPos);
}
// Create string
sb.append(_text.substring(startPos,_text.length()));
return sb.toString();
}
To substitute all the target with an empty line:
k = replace ( k, "<a target=\"_blank\" href=\"http://www.taxmann.com/directtaxlaws/fileopencontainer.aspx?Page=CIRNO&id=1999033000019320&path=/Notifications/DirectTaxLaws/HTMLFiles/S.O.193(E)30031999.htm&aa=\">", "");
No escape is needed for slash.

Categories