Java - Simplest way to get characters that come after substring inside string - java

How can I get a list of characters in a string that come after a substring? Is there a built-in String method for doing this?
List<String> characters = new ArrayList<>();
String string = "Grid X: 32";
// How can I get the characters that come after "Grid X: "?
I know you could do this with a loop, but is there another way that may be simpler?

Just grab the characters after the ": "
String string = "Grid X: 32"
int indexOFColon = string.indexOf(":");
String endNumber = string.subString(indexOFColon + 2);
So you get the index of the colon, which is 6 in this case, and then grab the substring starting 2 after that, which is where your number starts.

There are two possibilities:
Use a regular expression (regex):
Matcher m = Pattern.compile("Grid X: (\\d+)");
if (m.matches(string))
{
int gridX = Integer.parseInt(m.group(1));
doSomethingWith(gridX);
}
Use the substring method of the string:
int gridX = Integer.parseInt(string.substring(string.indexOf(':')+1).trim());
doSomethingWith(gridX);

Below code can be used for getting list of chacters :-
String gridString = "Grid X: 32";
String newString = gridString.subSubString(gridString.indexOf(gridString ) + gridString .length );
char[] charArray = newString.toCharArray();
Set nodup = new HashSet();
for(char cLoop : charArray){
nodup.add(cLoop);
}

There is more than one way to get this done. The simplest is probably just substring. But it is fraught with danger if the string doesn't actually start with "Grid X: "...
String thirtyTwo = string.substring( s.indexOf("Grid X: ") + "Grid X: ".length() );
Regex is pretty good at this too.

Related

Split string in reverse

I have a string sub1-sub2-sub3 which I want to split from right to left. Currently I am using split function like this which splits the string from left to right -
String str = "sub1-sub2-sub3";
System.out.println("Result :" + str.split("-", 2));
Elements in output :
sub1
sub2-sub3
Desired output :
sub1-sub2
sub3
Is there a way where I can split my string on - starting from right?
You could do a regex split on -(?!.*-):
String str = "sub1-sub2-sub3";
String[] parts = str.split("-(?!.*-)");
System.out.println(Arrays.toString(parts)); // [sub1-sub2, sub3]
The regex pattern used here will only match the final dash.
A generic solution as utility method that takes limit as input with java 8:
public List<String> splitReverse(String input, String regex, int limit) {
return Arrays.stream(reverse(input).split(regex, limit))
.map(this::reverse)
.collect(Collectors.toList());
}
private String reverse(String i){
return new StringBuilder(i).reverse().toString();
}
reverse() code taken from here
Input: sub1-sub2-sub3
Reverse input: 3bus-2bus-1bus
Split(rev,2): [3bus] , [2bus-1bus]
Reverse each: [sub3] , [sub1-sub2]
One way would be to reverse the string before the split and then reverse the resulting strings.
String str = "sub1-sub2-sub3";
Arrays.stream(StringUtils.reverse(str).split("-",2))
.map(StringUtils::reverse)
.forEach(System.out::println);
Output:
sub3
sub1-sub2
It won't yield the same result as requested but maybe it will help.
P.S. util class used is from apache: org.apache.commons.lang3.StringUtils
A quick and dirty solution i cam up with would be
String str = "sub1-sub2-sub3";
str = StringUtils.reverse(str);
String[] split = str.split("-", 2);
split[0] = StringUtils.reverse(split[0]);
split[1] = StringUtils.reverse(split[1]);
System.out.println("Result :" + split[0] + " #### " + split[1]);
another way would be java how to split string from end
The below solution worked for me fine :
str.substring(0, str.lastIndexOf("-"));
str.substring(str.lastIndexOf("-"));

Wrong Answer with Java

I'm a student that is learning Java, and I have this code:
lletres = lletres.replace(lletres.charAt(2), codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));
lletres is a string, and it's like this
lletres = "BBB"
The result is "CCC" and I only want to change the last B, so the result can be like this: "BBC".
Reading the documentation for String.replace should explain what happened here (I marked the relevant part in bold):
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
One way to solve it is to break the string up to the parts you want and then put it back together again. E.g.:
lletres = lletres.substring(0, 2) + (char)(lletres.charAt(2) + 1);
As others pointed replace() will replace all the occurrences which matched.
So, instead you can make use of replaceFirst() which will accept the regx
lletres = lletres.replaceFirst( lletres.charAt( 2 ) + "$", (char) ( lletres.charAt( 2 ) + 1 ) + "" )
You could use StringBuilder for your purpose:
String lletres = "BBB";
String codi = "CCC";
StringBuilder sb = new StringBuilder(lletres);
sb.setCharAt(2, codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));
lletres = sb.toString();
If you need to change only the last occurrence in the string, you need to split the string into parts first. I hope following snippet will be helpful to you.
String lletres = "BBB";
int lastIndex = lletres.lastIndexOf('B');
lletres = lletres.substring(0, lastIndex) + 'C' + lletres.substring(lastIndex+1);
This code will find index of last letter B and stores it in lastIndex. Then it splits the string and replaces that B letter with C letter.
Please keep in mind that this snippet doesn't check whether or not the letter B is present in the string.
With slight modification you can get it to replace whole parts of the string, not only letters. :)
Try this one.
class Rplce
{
public static void main(String[] args)
{
String codi = "CCC";
String lletres = "BBB";
int char_no_to_be_replaced = 2;
lletres = lletres.substring(0,char_no_to_be_replaced ) + codi.charAt(codi.indexOf(lletres.charAt(char_no_to_be_replaced )) + 1) + lletres.substring(char_no_to_be_replaced + 1);
System.out.println(lletres);
}
}
use this to replace the last character
lletres = lletres.replaceAll(".{1}$", String.valueOf((char) (lletres.charAt(2) + 1)));
suppose you have dynamic value at last index and you want to replace that value will increasing one then use this code
String lletres = "BBB";
int atIndex = lletres.lastIndexOf('B');
char ReplacementChar = (char)(lletres.charAt(lletres.lastIndexOf('B'))+1);
lletres= lletres.substring(0, atIndex)+ReplacementChar;
System.out.println(lletres);
output
BBC

How can i get the index of the first and last char in string?

Assume the below string :
String value = "161207CAD140000,0";
how can i get the index of the first char and the index of the last char for the substring CAD
notice that the size of the substring may be changed from 2 ,3 or etc chars i want the solution to be dynamic.
You can use String.indexOf(String str) function which will return starting indexof the "CAD". Then add one less then the length of String to find in the returned value, that will be your last character index of "CAD".
Something like this:
String value = "161207CAD140000,0";
String str = "CAD";
String datePart = value.substring(0, value.indexOf(str)); // for finding the date part
String amountStr = value.substring(value.indexOf(str) + str.length()); //for finding the amount part
System.out.println(datePart +" "+amountStr);`
Now suppose the String "CAD" is dynamic and you don't know what value it will have, in that case its better to use regex. Please see below code snippet:
String value = "161207CAD140000,0";
String patt = "[\\d,]+";
Pattern pattern = Pattern.compile(patt);
Matcher matcher = pattern.matcher(value);
while(matcher.find()){
System.out.println(matcher.group());
}
If any question let me know in comments. Hope it helps.
This would do the job for any string.
String value = "161207CAD140000,0";
String searchedString = "CAD"
int firstIndex = value.indexOf(searchedString);
int lastCharIndex = firstIndex + searchedString.length();
There are methods in the String class for such requirements. You can use the indexOf and lastIndexOf methods to get the positions. e.g
int index = value.indexOf("C"); //This returns 6
int lastIndex = value.lastIndexOf("D"); //this returns 8

How to extract integers from a complicated string?

I am having a hard time figuring with out. Say I have String like this
String s could equal
s = "{1,4,204,3}"
at another time it could equal
s = "&5,3,5,20&"
or it could equal at another time
s = "/4,2,41,23/"
Is there any way I could just extract the numbers out of this string and make a char array for example?
You can use regex for this sample:
String s = "&5,3,5,20&";
System.out.println(s.replaceAll("[^0-9,]", ""));
result:
5,3,5,20
It will replace all the non word except numbers and commas. If you want to extract all the number you can just call split method -> String [] sArray = s.split(","); and iterate to all the array to extract all the number between commas.
You can use RegEx and extract all the digits from the string.
stringWithOnlyNumbers = str.replaceAll("[^\\d,]+","");
After this you can use split() using deliminator ',' to get the numbers in an array.
I think split() with replace() must help you with that
Use regular expressions
String a = "asdf4sdf5323ki";
String regex = "([0-9]*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(a);
while (matcher.find())
{
String group = matcher.group(1);
if (group.length() > 0)
{
System.out.println(group);
}
}
from your cases, if the pattern of string is same in all cases, then something like below would work, check for any exceptions, not mentioned here :
String[] sArr= s.split(",");
sArr[0] = sArr[0].substring(1);
sArr[sArr.length()-1] =sArr[sArr.length()-1].substring(0,sArr[sArr.length()-1].length()-1);
then convert the String[] to char[] , here is an example converter method
You can use Scanner class with , delimiter
String s = "{1,4,204,3}";
Scanner in = new Scanner(s.substring(1, s.length() - 1)); // Will scan the 1,4,204,3 part
in.useDelimiter(",");
while(in.hasNextInt()){
int x = in.nextInt();
System.out.print(x + " ");
// do something with x
}
The above will print:
1 4 204 3

How can I split two digit into two different strings?

I have month in, which contains a value such as 12. I am trying to split it into two different strings e.g. a=1 and b=2. How do I do this?
There are several ways to do this.
// Working with Strings ------
String str = "12";
// Get char array
char[] chars = str.toCharArray();
// Two substrings
String firstStr = str.substring(0,1);
String secondStr = str.substring(1,2);
// Working with ints ---------
int i = 12;
int firstInt = i / 10; // Divide
int secondInt = i % 10; // Modulo
Use String.charAt(index) method to return a character and use Character.toString(char) to convert it to String.
Simplest way might be to convert it to a String and then use charAt() to read the characters one by one.
Sounds like a homework question :)
String x = "12";
String[] x_arr= x.split("");
your chars will be located in
x[1]
x[2]
and eventually you can go on with the index if you passed a longer string (like a year).
Just avoid x[0] because it is an empty string.
String splits[] = "12".split("#?") would work.
Use :
str.split("\\w.+")
For Example :
String[] parts = "12".split("\\w.+");
String a = parts[0]
Strign b = parts[1]
You can Take a look here
http://www.roseindia.net/regularexpressions/splitting-string.shtml
Try this:
String input = "12";
System.out.println(input.charAt(0)); // gives '1'
System.out.println(input.charAt(1)); // gives '2'
Furthermore, if you wish to have '1' and '2' as Strings (not as chars), you can do this :
String firstDigit = input.charAt(0) + "";
String secondDigit = input.charAt(1) + "";
Good luck !
Konstantin
EDIT: Lets assume that 'month' is variable of type java.util.Date. Then:
String monthToString = new SimpleDateFormat("MM").format(month);
String firstDigit = monthToString.charAt(0) + "";
String secondDigit = monthToString.charAt(1) + "";
You can use the method substring of class String.
There is the documentation: http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#substring(int, int)
The algorithm is not complex ;)

Categories

Resources