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

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

Related

How to print the specific element in the splitted values in selenium java

String ActualValue = element.getAttribute("class");
String[] SplittedValue =ActualValue.split("");
Output: object_selected object_notselected
How to print the value object_selection in System.out.println(" ");
See, this
SplittedValue
is string array, and you can print array in multiple ways:
String actualValue = driver.findElement(By.xpath("//")).getAttribute("class");
String[] splittedValue = actualValue.split("");
System.out.println("Length of array:" + splittedValue.length);
if (splittedValue.length > 0) {
for(String str: splittedValue) {
System.out.println(str);
}
}
else {
System.out.println("Since lenght is zero, split was not properly, you may wanna check what you are passing in split method");
}
Not sure why you are using split like this split(""), probably you are looking for this split(" ")
Also if you are sure about the string elements, then you can directly print
them like this (Not recommended):
String actualValue = driver.findElement(By.xpath("//")).getAttribute("class");
String[] splittedValue = actualValue.split(" ");
System.out.println(splittedValue[0]);
System.out.println(splittedValue[1]);
You were close enough. Once you retrieve the value of classname i.e. object_selected object_notselected you can invoke split() with respect to the space character as the delimiter as follows:
String ActualValue = element.getAttribute("class");
// ActualValue = "object_selected object_notselected"
String[] SplittedValue = ActualValue.split(" ");
//printing object_selected
System.out.println(SplittedValue[0]);
//printing object_notselected
System.out.println(SplittedValue[1]);

String Manipulation in java 1.6

String can be like below. Using java1.6
String example = "<number>;<name-value>;<name-value>";
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String abc = "+17005554141;qwq=123454";
String abc = "+17005554141";
I want to remove qwq=1234 if present from String. qwq is fixed and its value can VARY like for ex 1234 or 12345 etc
expected result :
String abc = "+17005554141;ddd=ewew;otg=383";
String abc = "+17005554141"; \\removed ;qwq=123454
String abc = "+17005554141";
I tried through
abc = abc.replaceAll(";qwq=.*;", "");
but not working.
I came up with this qwq=\d*\;? and it works. It matches for 0 or more decimals after qwq=. It also has an optional parameter ; since your example seems to include that this is not always appended after the number.
I know the question is not about javascript, but here's an example where you can see the regex working:
const regex = /qwq=\d*\;?/g;
var items = ["+17005554141;qwq=123454",
"+17005554141",
"+17005554141;qwq=1234;ddd=ewew;otg=383"];
for(let i = 0; i < items.length; i++) {
console.log("Item before replace: " + items[i]);
console.log("Item after replace: " + items[i].replace(regex, "") + "\n\n");
}
You can use regex for removing that kind of string like this. Use this code,
String example = "+17005554141;qwq=1234;ddd=ewew;otg=383";
System.out.println("Before: " + example);
System.out.println("After: " + example.replaceAll("qwq=\\d+;?", ""));
This gives following output,
Before: +17005554141;qwq=1234;ddd=ewew;otg=383
After: +17005554141;ddd=ewew;otg=383
.* applies to multi-characters, not limited to digits. Use something that applies only to bunch of digits
abc.replaceAll(";qwq=\\d+", "")
^^
Any Number
please try
abc = abc.replaceAll("qwq=[0-9]*;", "");
If you don't care about too much convenience, you can achieve this by just plain simple String operations (indexOf, replace and substring). This is maybe the most legacy way to do this:
private static String replaceQWQ(String target)
{
if (target.indexOf("qwq=") != -1) {
if (target.indexOf(';', target.indexOf("qwq=")) != -1) {
String replace =
target.substring(target.indexOf("qwq="), target.indexOf(';', target.indexOf("qwq=")) + 1);
target = target.replace(replace, "");
} else {
target = target.substring(0, target.indexOf("qwq=") - 1);
}
}
return target;
}
Small test:
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String def = "+17005554141;qwq=1234";
System.out.println(replaceQWQ(abc));
System.out.println(replaceQWQ(def));
outputs:
+17005554141;ddd=ewew;otg=383
+17005554141
Another one:
abc.replaceAll(";qwq=[^;]*;", ";");
You must to use groups in replaceAll method.
Here is an example:
abc.replaceAll("(.*;)(qwq=\\d*;)(.*)", "$1$3");
More about groups you can find on: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

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.

ReplaceAll method to replace an array of String in java

I have an array of String like: "11456811193903(admin 2016-03-01 11:16:23) (Sale)", I want to remove " (Sale)" from the array String. How to replace this in an array of Strings?
Original String:
String[] fileName = {"11456811193903(admin 2016-03-01 11:16:23) (Sale)"};
After replacing:
fileName:11456811193903(admin 2016-03-01 11:16:23)
Bahramdun's solution works perfectly fine, but if you are a fan of Java 8 streams you might want to use this:
String[] fileName = {...};
fileName = Arrays.stream(fileName)
.map(s -> s.replace("(Sale)", ""))
.toArray(size -> new String[size]);
You can try this: If your array has more than one element, then you can loop over the array as shown below. And if it is only one sentence, then you can directly remove the (Scale) and assign it again to the String fileName
String[] fileName = {"11456811193903(admin 2016-03-01 11:16:23) (Sale)"};
for (int i = 0; i < fileName.length; i++) {
fileName[i] = fileName[i].replaceAll("\\(Sale\\)", "");
}
System.out.println("fileName = " + Arrays.toString(fileName));
And it is the result:
fileName = [11456811193903(admin 2016-03-01 11:16:23)]

Usage of the java function 'split()

I would like to split the word in java based on the delimeter'-'when it appeared last.
I am expecting the result as "sweet_memory_in" and "everbodylife#gmail.com". Do we have any inbuilt function in java.
Complete word is sweet_memory_in_everbodylife#gmail.com
String s = "sweet_memory_in_everbodylife#gmail.com";
String first = s.substring(0,s.lastIndexOf("_"));
String second = s.substring(s.lastIndexOf("_")+1 );
try this
String s = "sweet_memory_in_everbodylife#gmail.com";
String s1 = s.substring(0,s.lastIndexOf("_"));
String s2 = s.substring(s.lastIndexOf("_")+1,s.length());
Regex may help. Other way is to get the last index of _ and use substring to split it.
Try out this code :
String data = "sweet_memory_in_everbodylife#gmail.com";
int lastIndex = data.lastIndexOf("_");
String firstSplit = data.substring(0, lastIndex);
String secondSplit = data.substring(lastIndex + 1, data.length());
System.out.println(firstSplit);
System.out.println(secondSplit);
Try this my friend (Javascript Codes):
var str = 'sweet_memory_in_everbodylife#gmail.com';
var arr1 = str.substring(str.lastIndexOf("_")).split("_");
var arr2 = str.split("_"+arr1[1]);
alert(arr2[0] +" --> "+arr1[1]);

Categories