Find index of a string array - java

I have a string :
String str = "sces123 4096 May 27 16:22 sces123 abc";
I want to get sces123 abc from the string. My code is :
String[] line = str.split("\\s+");
String name = str.substring(str.indexOf(line[5]));
It returns the whole string.
Dont know how to do.
any help appreciated!

Your code should be
String[] line = str.split("\\s+");
String name = str.substring(str.lastIndexOf(line[5]));
because str.lastindexOf(line[5]) returns 0 and then the substring returns the whole String.

In your case you just need to change str.indexOf -> str.lastIndexOf.

This is one easy solution :
String str = "sces123 4096 May 27 16:22 sces123 abc";
//split spaces
String[] line = str.split(" ");
//get 2 last columns
String name = (line[5] + " " + line[6]);
System.out.println(name);

As Glorfindel said in the comment sces123 which is the content of if line[5] also contain as the first substring in the main String str. That why you are getting the full string.
Whats really happening here is:
indexOf( line[ 5 ]) --> returning 0
str.substring(0) --> returning substring form 0 to last which is the main string
If you are only doing the hard codded things then i don't see the purpose of you here.
But What you want you get in this way (if it serve your purpose ) :
String name = str.substring( str.indexOf( line[ 5 ]+" "+line[6] ) );

Try This:
String str = "sces123 4096 May 27 16:22 sces123 abc";
String[] line = str.split("\\s+");
System.out.println(str.substring(str.lastIndexOf(line[5])));

You could use a Matcher to find the end of the 5th match:
String str = "sces123 4096 May 27 16:22 sces123 abc";
Pattern p = Pattern.compile("\\s+");
Matcher m = p.matcher(str);
for (int i = 0; i < 5; i++) {
m.find();
}
String name = str.substring(m.end());
In my opinion this is better than using lastIndexOf on to concatenating elements at indices 5 and 6, for the following reasons:
It does not require line[5] to be the last occurence of that string.
Using lastIndexOf doesn't work for input
"sces123 4096 May 27 16:22 sces123 sces123"
It also works for seperator strings of arbirtrary length.
Using line[ 5 ]+" "+line[6] doesn't work for input
"sces123 4096 May 27 16:22 sces123 abc"
It does not require the number elements after the split to be 7.
Using line[ 5 ]+" "+line[6] doesn't work for input
"sces123 4096 May 27 16:22 sces123 abc def"

Related

Convert text string to octal string

I need to convert a text string to an WinANSIEncoding compliant (Windows code page 1252) octal string (using Java).
"André" should become "101 156 144 162 351" or "\101\156\144\162\351".
I could use a simple string search and replace for each character in the list of allowed characters, but this would probably not be the fastest solutions.
Does anyone know how this should be done?
Thanx
TM
Ps
https://cryptii.com/text-octal
The toOctalString(int i) will help :
Using Streams
String str ="André";
String toOctal = str.chars().boxed().map(Integer::toOctalString)
.collect(Collectors.joining(" "));
System.out.println(toOctal); // 101 156 144 162 351
Workable Demo
Basic loop
String str ="André";
String toOctal ="";
for(char c : str.toCharArray()){
toOctal += Integer.toOctalString(c)+" ";
}
System.out.println(toOctal);

Split complex string within a muliple sub string with same special character

I am trying to parse the string with semicolon with multiple substrings, here are the example
String temp = "SIM1_TM_4G3G2G_DE;ANY_RAT;TCNAME_Flight_Mode_Toggle;TIME_60;120;90;30"
Expected output required would be to display only values after the TIME_:
60
120
90
30
I have tried with the following code it did not do the following need
String[] args_val=temp.split(";");
log("STARTING THE LOOP");
for(int ix=0; ix<args_val.length;ix++)
{
log("args_val["+ix+"]-" +args_val[ix]);
//TIME is considered in seconds
if(args_val[ix].contains(TIME"))
{
log("args_val[ix] length -" +args_val[ix].length());
String sTime = args_val[ix].substring(args_val[ix].indexOf("TIME_") +5, args_val[ix].length());
log("print sTime-" +sTime);
}
}
Try this:
String output = temp.substring(temp.indexOf("TIME_") + 5)
.replaceAll(";", "");
You may remove all the substring from start till and including ;TIME_ with the .*;TIME_ regex (note that the .* is a greedy dot matching pattern and will match from the start of the string till the last ;TIME_ on the line), and then split the rest with ;:
String temp = "SIM1_TM_4G3G2G_DE;ANY_RAT;TCNAME_Flight_Mode_Toggle;TIME_60;120;90;30";
String[] res = temp.replaceFirst(".*;TIME_", "").split(";");
System.out.println(res[0]);
System.out.println(res[1]);
System.out.println(res[2]);
System.out.println(res[3]);
See the Java demo
This will work if the string you mention is always in this format.

replace only some characters in a string

I am looking for a way in Java to replace a matched character from a sequence without a loop.
Example
String x = ""
String pattern = "12"
String ex1 = "1254"
x = ex1.replace(pattern, "");
System.out.print(x)
Output:
54
In this case 1254 a match is found: 12
However,
String x = ""
String pattern = "12"
String ex1 = "154"
x = ex1.replace(pattern, "");
System.out.print(x)
Output:
154
In this case no replacement takes place.
The desired output in this case would be:
54
because only 1 is found from the pattern
This is because the pattern should fully match in the word. However, is there a function where only the matched characters from the pattern will be replaced?
How about using a character class
x = ex1.replaceAll("[12]", "");

how to put String values into new Line on getting spaces in java

Hii Guys !!!
I have a string with values like 69 17 17 16 2 1 1 26 26 56 56 69 20 19 20 etc .Now As per my need i have to put these values into new String with each values in new line as after each value space is there ..
Any help will be highly appreciated..
Thanx in advance...
String newStr = origStr.replaceAll(" ", " \n");
You should split the String using a specific separator into a List.
Then print out the List using the format required.
This helps when tomorow the String contains digits, decimals, text, etc or they want the text in another format.
String source = "69 17 17 16 2 1 1 26 26 56 56 69 20 19 20";
String[] splitted = source.split(" ");
StringBuilder sb = new StringBuilder();
for (String split : splitted){
sb.append(split).append(System.getProperty("line.separator"));
}
System.out.println(sb.toString());

Why Matcher fails for Strings obtained or provide at Runtime in Java?

Hi I was recently developing a code where i had to extract the last 3 group of digits. So i used pattern to extract the data. But i failed to understand. CAN any one help me to understand it ??
String str ="EGLA 0F 020";
String def = "ALT 1F 001 TO ALT 1F 029";
String arr[] = def.split("TO");
String str2 = arr[0];
System.out.println("str2:"+str2);
Pattern pt = Pattern.compile("[0-9][0-9][0-9]$");
Matcher m1 = pt.matcher(str);
Matcher m2 = pt.matcher(str2);
boolean flag = m1.find();
boolean flag2 = m2.find();
if(flag)
System.out.println("first match:::"+m1.group(0));
else
System.out.println("Not found");
if(flag2)
System.out.println("first match:::"+m2.group(0));
else
System.out.println("Not found");
The output produced for the above code is As follows:::
str2:ALT 1F 001
first match:::020
Not found
Please Do reply iam stuck here ??
It's because when you split you have a trailing space.
String str = "EGLA 0F 020";
String str2 = "ALT 1F 001 ";
// ^ trailing space
You could fix it a number of ways. For example:
by splitting on " TO "
trimming the result
allowing trailing spaces in your regular expression.
For example, this change would work:
String arr[] = def.split(" TO ");
If you notice your split take effect only on the letters "TO", it means str2 pattern is "ALT 1F 001 ".
To resolve this you can try to split on "\s*TO\s*" instead of "TO" so that any spaces surrounding the work TO would be removed too. Another solution would be to replace your pattern "[0-9][0-9][0-9]$" with "[0-9][0-9][0-9]" without the final $, so that it would accept ending spaces on your String.
Try this pattern:
Pattern pattern = Pattern.compile("[0-9][0-9][0-9]\\s*$");
or
Pattern pattern = Pattern.compile("[0-9]{3}\\s*$");

Categories

Resources