Dinesh Reddy
Dinesh Reddy

Reputation: 25

Removing anything after number in string

How to remove characters after number in android

suppose my strings are

A1SS
A2SS
2SS
3SS
5SS

My Output Should be

A1
A2
2
3
5

Upvotes: 1

Views: 993

Answers (10)

Roma Khomyshyn
Roma Khomyshyn

Reputation: 1152

try it

output = output.replaceAll("[^\\d]*$", "");

[^\d]*$ - this regex deletes all symbols after the last number

DEMO

Upvotes: 0

Kiran Benny Joseph
Kiran Benny Joseph

Reputation: 6813

Simple way: More faster than other ways

public String getData(String val){
        String dat =val;
        boolean intFound=false;
        for (int i=0; i < val.length(); i++) {
            char c = val.charAt(i);
            if (Character.isDigit(c)) {
                dat = val.substring(0, i + 1);
                intFound = true;
            } else if (intFound) {
                break;
            }
        }
        return dat;
    }

Use above method and

String data=getData("A1SS");

Simplicity

it will work your all cases

  • "A434AS" RETURNS "A434".

  • "3FG" RETURNS "3".

  • "ERT45" RETURNS "ERT45".

  • "SDF34DFG2" RETURNS "SDF34" THANKS TO Ole V.V

Logic:

  1. passing string to method.
  2. Detecting integer position in String
  3. Ignoring another charecter which comes after integer
  4. returning substring to that position

Thanks to Mr. Rabbit

Upvotes: 0

Anonymous
Anonymous

Reputation: 86232

I think it’s simplest to use a regular expression (regex or regexp among friends):

private static final Pattern PAT_UNTIL_NUMBER = Pattern.compile("^[^0-9]*[0-9]+");

public static String removeCharsAfterNumber(String stringWithNumber) {
    Matcher m = PAT_UNTIL_NUMBER.matcher(stringWithNumber);
    if (m.find()) {
        return m.group();
    } else {
        throw new IllegalArgumentException("No number in string " + stringWithNumber);
        // or depending on requirements, may just return stringWithNumber
    }
}

Given the strings in your question, this method produces the output you asked for. It takes into account that your number may consist of more than one digit. For example, A27B becomes A27. It truncates after the first number if there are more than one, for example, A7B4SS gives A7. If you want different behaviour, it’s probably not difficult to modify the regular expression to your requirements.

I will not explain the basics of regexps here. There are some tutorials out there, use your search engine. You will of course want to understand what is happening in the code.

If for one reason or another you cannot or do not want to use a regexp, some of the other answers demonstrate how to hand program a solution. Here’s my version for good measure. I hope the comments explain what is going on, and I myself consider it simple and straightforward.

    int index = 0;
    // find the number
    while (index < stringWithNumber.length() && ! Character.isDigit(stringWithNumber.charAt(index))) {
        index++;
    }
    if (index == stringWithNumber.length()) { // no number found
        throw new IllegalArgumentException("No number in string " + stringWithNumber);
    }
    // find end of number
    while (index < stringWithNumber.length() && Character.isDigit(stringWithNumber.charAt(index))) {
        index++;
    }
    return stringWithNumber.substring(0, index);

Upvotes: 0

Oghli
Oghli

Reputation: 2340

simple way :

         String input="mhd60oug",result;
         int LastDigitid = -1;
       for(int i=0; i < input.length(); i++){
           char c = input.charAt(i);
           if(Character.isDigit(c)){
               LastDigitid = i;
           }
       }
       if(LastDigitid != -1){
          result = input.substring(0,LastDigitid+1);
       }
       else{
           result = input;
       }
       System.out.println(result);

update :

this way will only work after the last number in a String.the asker didn't explain exactly which case he wants in his problem.

there are several main cases :

  1. String with more than one number like A1SS23BD:

in this case which exactly the result you want A1 or A1SS23?

  1. String with only one number like 2SS
  2. String that doesn't contain any number like ASS
  3. String with only a number like 23

Upvotes: 1

davidxxx
davidxxx

Reputation: 131346

1) You can use regex to achieve your need or iterate on the String to compute the end index on which you could perform a substring.

2) In your examples you don't show cases whereyou truncate the String after a series of digit.
I will show you both solutions

3) With iteration over the String, the general idea is : either the searched pattern was not detected, so you return the original string, either it it was detected, you return the substring associated to.

Here is a class that provides one method for each case and with a sample ex :

public class TruncateStringAfterDigit {

    public static void main(String[] args) {

        String s = "ba123";

        String valueTrimedAfterDigits = getValueTrimedAfterDigits(s);
        System.out.println(valueTrimedAfterDigits);

        String valueTrimedAfterDigit = getValueTrimedAfterOneDigit(s);
        System.out.println(valueTrimedAfterDigit);
    }

    private static String getValueTrimedAfterDigits(String s) {

        boolean isAtLeastANumberFound = false;

        for (int i = 0; i < s.length(); i++) {

            if (Character.isDigit(s.charAt(i))) {
                isAtLeastANumberFound = true;
            }

            else if (isAtLeastANumberFound) {
                return s.substring(0, i+1);
            }
        }

        return s;
    }

    private static String getValueTrimedAfterOneDigit(String s) {

        for (int i = 0; i < s.length(); i++) {

            if (Character.isDigit(s.charAt(i))) {
                return s.substring(0, i + 1);
            }
        }

        return s;
    }
}

The rendered output :

ba123

ba1

Upvotes: 0

phoenix
phoenix

Reputation: 496

You can use below method, that will work in all the cases.

    public String getModifiedString(String string) {
        String modifiedString = "";

        for(int index = 0; index < string.length(); index++) {
            char currentChar = string.charAt(index);
            if(Character.isLetter(currentChar)) {
                modifiedString += currentChar;
            } else if(Character.isDigit(currentChar)) {
                modifiedString += currentChar;

                for(int digitIndex = index+1; digitIndex < string.length(); digitIndex++) {
                    if(Character.isDigit(string.charAt(digitIndex))) {
                        modifiedString += string.charAt(digitIndex);
                    }
                }

                return modifiedString;
            }
        }

        return modifiedString;
    }

You can try it by just pasting below it in your code.

String[] stringArray = new String[]{"A1SS", "A2SS", "2SS", "AA222SS", "AN33"};
Log.d("---SO", " str 1: " + getModifiedString(stringArray[0]));
Log.d("---SO", " str 2: " + getModifiedString(stringArray[1]));
Log.d("---SO", " str 3: " + getModifiedString(stringArray[2]));
Log.d("---SO", " str 4: " + getModifiedString(stringArray[3]));
Log.d("---SO", " str 5: " + getModifiedString(stringArray[4]));

Upvotes: 0

Meo_3_the
Meo_3_the

Reputation: 11

If the input is AB22CD, you want the result is AB22 or just AB2.
Edit: so maybe you can use this code:

public String removeCharactersAfterNumber(String input) {
    int index;
    for (index = 0; index < input.length(); index++) {
        if (input.charAt(index)  >= '0' && input.charAt(index) <= '9'){
            break;
        }
    }
    while (input.charAt(index)  >= '0' && input.charAt(index) <= '9') index++;
    return input.substring(0, index);
}

Upvotes: -1

Harry T.
Harry T.

Reputation: 3527

Use for to do it.

UPDATE case AA22S to AA22. Thanks @meo_3_the.

For example:

    String s = "A1SS";
    StringBuilder newStr = new StringBuilder("");
    boolean detected = false;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) >= '0' && s.charAt(i) <= '9'){
            newStr.append(s.charAt(i));
            detected = true;
        }else{
            if (!detected)
                newStr.append(s.charAt(i));
            else
                break;
        }
    }

Result String: newStr.toString();

Upvotes: 1

Waqas Ahmed
Waqas Ahmed

Reputation: 153

i think this might help you.

String value = your_string.replaceAll("[^0-9]","");

Upvotes: 1

Asutosh Panda
Asutosh Panda

Reputation: 1473

let us suppose you are getting the value in a variable called output.

To remove one SS in a String, you can use replace

output = output.replace("SS", "");

Or if you have to remove more than one SS in a String, you can use replaceAll

output = output.replaceAll("SS", "");

Upvotes: 0

Related Questions