-4

I am new to Java. I want to ask how to search for a general sub-string within a given string.

For example:-
In the string 12345.67 I want to search for the sub-string .67
And in the string 1.00 I want to search for the string .00.

I basically want to search for the string after the radical (.), provided the number of characters after radical are only 2.

According to my knowledge search for general sub-string is not possible, I thereby asked for your help.

I wish to print the input (stored in the database) , a floating point number, into Indian Currency format, i.e, comma separated.
I even looked at various previous posts but none of them seemed to help me as almost everyone of them failed to produce the requite output for decimal point

4 Answers4

4

According to my knowledge search for general sub-string is not possible

So you may learn a bit more, here String substring(int beginIndex) method :

String str = "12345.67";
String res = str.substring(str.indexOf('.')); // .67

If you want to check that there is only 2 digits after . :

String str = "12345.67";
String res = str.substring(str.indexOf('.') + 1); // 67
if(res.length() == 2)
    System.out.println("Good, 2 digits");
else
    System.out.println("Holy sh** there isn't 2 digits);
azro
  • 53,056
  • 7
  • 34
  • 70
1

You can use split plus the substring to achieve your objective

String test = "12345.67";
System.out.println(test.split("\\.")[1].substring(0,2));

In the split function, you can pass the regex with which you could give the separator and in a substring function with the number of characters you want to extract

Sunder R
  • 1,074
  • 1
  • 7
  • 21
  • 1
    Hi Sunder! Thanks for the reply. Being a novice myself could you please elaborate your code so it's easier for me to understand – Alpha Sniper Jun 22 '18 at 07:24
  • the substring is not needed and will fail currently. -> `StringIndexOutOfBounds` – Lino Jun 22 '18 at 07:26
  • since in the question he mentioned that , he want the control over the number of charachters after the radical, substring will help in achieve that. – Sunder R Jun 22 '18 at 07:28
0

Next to the answer provided from @azro you may also use regex:

String string = "12345.67";
Pattern ppattern = Pattern.compile("\\d+(\\.\\d{2})");
Matcher matcher = pattern.matcher(string);
if(matcher.matches()){
   String sub = matcher.group(1);
   System.out.println(sub);
}

Which prints:

.67
Lino
  • 19,604
  • 6
  • 47
  • 65
0
String str = "12345.67";
String searchString = "." + str.split("\\.")[1];
if(str.contains(searchString)){
    System.out.println("The String contains the subString");
}
else{
    System.out.println("The String doesn't contains the subString");
}
SriAji
  • 101
  • 6