C. Suarez
C. Suarez

Reputation: 11

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.

Upvotes: 0

Views: 814

Answers (3)

Jorge Campos
Jorge Campos

Reputation: 23361

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.

Upvotes: 1

Bunti
Bunti

Reputation: 1760

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

Upvotes: 2

Andreas
Andreas

Reputation: 159106

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.

Upvotes: 2

Related Questions