C. Suarez February 2016

How to make substring() read a string until a certain character?

I want to create a substring say:

String s1 = "derp123";

s2 = s1.substring(0, *index where there's a number*);

Is there any way I can achieve this other than by using the replaceAll method?

I don't want to replace all the numbers in the String, I want to stop reading the string once the method detects a number 0-9.

Answers


Bunti February 2016

Here is what you want.

String s1 = "derp123";
String patternStr = "[0-9]";
Matcher matcher = Pattern.compile(patternStr).matcher(s1);
if (matcher.find()) {
   System.out.println(s1.substring(0, matcher.start()));
}

And this will give you the string part without numbers


Andreas February 2016

For this, regular expression is your friend.

I'll just show you the code for your example, but you should learn more about the power (and limitations) of regular expressions. See javadoc of Pattern.

String s1 = "derp123";
Matcher m = Pattern.compile("^\\D*").matcher(s1);
if (m.find())
    System.out.println(m.group()); // prints: derp

Note that the replaceAll() method shown in comments is also using a regular expression.


Jorge Campos February 2016

Since OP said that he did not want to use replace and therefore regex this is my suggestion. Note, the REGEX version already given is much more elegant in my opinion I'm only providing this to show that are others ways to do so.

String s1 = "blahblah1234";
String s2 = s1.substring(0, firstNumberPos(s1));
System.out.println(s2);

And the firstNumberPos definition

public static int firstNumberPos(String str){
    for ( int i=0; i<str.length(); i++ ){
        if ( str.charAt(i) >= '0' && str.charAt(i) <= '9'){
            return i;
        }
    }
    return str.length();
}

Note that I didn't care about the null points, you still have to check it.

Post Status

Asked in February 2016
Viewed 1,903 times
Voted 5
Answered 3 times

Search




Leave an answer