Remove characters in a string

wondering.. anyone knows how to remove characters in a string
e.g.
string: applepie
after removing last 3 chars become "apple"
thanks...

That of course will only work for this example. Better solution is to use indexOf() to locate the position of the string you wish to remove. If the string you wish to remove is in the middle, then you will have to do a bit of extra work and concat two substrings.

Similar Messages

  • Removing characters from a String (concats, substrings, etc)

    This has got me pretty stumped.
    I'm creating a class which takes in a string and then returns the string without vowels and without even numbers. Vowels and even characters are considered "invalid." As an example:
    Input: "hello 123"
    Output: "hll 13"
    The output is the "valid" form of the string.
    Within my class, I have various methods set up, one of which determines if a particular character is "valid" or not, and it is working fine. My problem is that I can't figure out how to essentially "erase" the invalid characters from the string. I have been trying to work with substrings and the concat method, but I can't seem to get it to do what I want. I either get an OutOfBoundsException throw, or I get a cut-up string that just isn't quite right. One time I got the method to work with "hello" (it returned "hll") but when I modified the string the method stopped working again.
    Here's what I have at the moment. It doesn't work properly for all strings, but it should give you an idea of where i'm going with it.
    public String getValidString(){
              String valid = str;
              int start = 0;
              for(int i=0; i<=valid.length()-1; i++){
                   if(isValid(valid.charAt(i))==false){
                             String sub1 = valid.substring(start, i);
                             while(isValid(valid.charAt(i))==false)
                                  i++;
                             start=i;
                             String sub2 = valid.substring(i, valid.length()-1);
                             valid = sub1.concat(sub2);
              return valid;
         }So does anybody have any advice for me or know how I can get this to work?
    Thanks a lot.

    Thansk for the suggestions so far, but i'm not sure how to implement some of them into my program. I probably wasn't specific enough about what all I have.
    I have two classes. One is NoVowelNoEven which contains the code for handling the string. The other is simply a test class, which has my main() method, used for running the program.
    Here's my class and what's involved:
    public class NoVowelNoEven {
    //data fields
         private String str;
    //constructors
         NoVowelNoEven(){
              str="hello";
         NoVowelNoEven(String string){
              str=string;
    //methods
         public String getOriginal(){
              return str;
         public String getValidString(){
              String valid = str;
              int start = 0;
              for(int i=0; i<=valid.length()-1; i++){
                   if(isValid(valid.charAt(i))==false){
                             String sub1 = valid.substring(start, i);
                             while(isValid(valid.charAt(i))==false)
                                  i++;
                             start=i;
                             String sub2 = valid.substring(i, valid.length()-1);
                             valid = sub1.concat(sub2);
              return valid;
         public static int countValidChar(String string){
              int valid=string.length();
              for(int i=0; i<=string.length()-1; i++){
                   if(isNumber(string.charAt(i))==false){
                        if((upperVowel(string.charAt(i))==true)||lowerVowel(string.charAt(i))){
                             valid--;}
                   else if(even(string.charAt(i))==true)
                        valid--;
              return valid;
         private static boolean even(char num){
              boolean even=false;
              int test=(int)num-48;
              if(test%2==0)
                   even=true;
              return even;
         private static boolean isNumber(char chara){
              boolean number=false;
              for(int i=0; i<=9; i++){
                   if((int)chara-48==i){
                        number=true;
              return number;
         private static boolean isValid(char chara){
              boolean valid=true;
              if(isNumber(chara)==true){
                   if(even(chara)==true)
                        valid=false;
              if((upperVowel(chara)==true)||(lowerVowel(chara)==true))
                   valid=false;
              return valid;
    }So in my test class i'd have something like this:
    public class test {
    public static void main(String[] args){
         NoVowelNoEven test1 = new NoVowelNoEven();
         NoVowelNoEven test2 = new NoVowelNoEven("hello 123");
         System.out.println(test1.getOriginal());
         //This prints hello   (default constructor string is "hello")
         System.out.println(test1.countValidChar(test1.getOriginal()));
         //This prints 3
         System.out.println(test1.getValidString());
         //This SHOULD print hll
    }

  • Removing characters from a String

    Hi!
    I have a large String that has some unwanted characters in it that I want to remove. Here is an example:
    AA1lbmNvZGVkUGFy\015\012YW1zdAACW0JbABBlbm5MQ2Is there any method I can use to remove the characters \015\012 from the String. I looked at the method String.replace(char, char); but this is unsuitable because I can only remove one charater at a time an I may have this character occuring legitimately elsewhere in my String. Would it be possible in some way to traverse the String and identify the pattern of \015\012 and remove that.
    I'd appreciate any help,
    Thanks
    Chris

    Specifically,  str = str.replaceAll("\\\\01[25]", "");The replaceAll method is only available in v1.4.0 or later.

  • Remove $%&* characters from a String

    Hi,
    I have the following program that is supposed to detect a subsequence from a String (that contains $ signs) and remove it. This is a bit tricky, since because of $ signs, the replaceAll method for String does not work. When I use replaceAll for removing the part of the String w/ no $ signs, replaceAll works perfectly, but my code needs to cover the $ signs as well.
    So far, except for replaceAll, I have tried the following, with the intent to first remove $ signs from only that specific sequence in the String (in this case from $d $e $f) and then remove the remaining, which is d e f.
    If anyone has any idea on this, I would greatly appreciate it!
    Looking forward to your help!
    public class StringDivider {
         public static void main(String [] args)
              String symbols = "$a $b $c $d $e $f $g $h $i $j $k l m n o p";
             String removeSymbols = "$d $e $f";
             int startIndex = symbols.indexOf(removeSymbols);
             int endIndex = startIndex + removeSymbols.length()-1;
             for(int i=startIndex;i<endIndex+1;i++)
                  if(symbols.charAt(i)=='$')
                       //not sure what to do here, I tried using replace(oldChar, newChar), but I couldn't achieve my point, which is to
                       //delete $ signs from the specific sequence only (as opposed to all the $ signs)
             System.out.println(symbols);
    }

    A little modification on the last version:
    This one's more accurate.
    public class StringDivider {
         public static void main(String [] args){
              String symbols = "$a $b $c $d $e $f $g $h $i $j $k l m n o p";
                  String removeSymbols = "$d $e $f $g";
                  if(symbols.indexOf(removeSymbols)!=-1)
                       if(removeSymbols.indexOf("$")!=-1)
                            removeSymbols = removeSymbols.replace('$', ' ').trim();
                            removeSymbols = removeSymbols.replaceAll("[ ]+", " ");
                            String [] symbolsWithoutSpecialChars = removeSymbols.split(" ");
                            for(int i=0;i<symbolsWithoutSpecialChars.length;i++)
                                 symbols = symbols.replaceAll("[\\$]*"+symbolsWithoutSpecialChars, "");
                             symbols = symbols.replaceAll("[ ]+", " ");
                   else
                        symbols = symbols.replaceAll(removeSymbols, "");
              symbols = symbols.trim();
              System.out.println(symbols);

  • Split/remove characters for a string token

    How can a string token i.e. 2-234-56723-4 have the - removed so that the token is left with 2234567234?
    I tried to split it using "-" but that obviously doesnt work, because 234 will be a token, I just want to remove the - from the token.
    advice please.

    endasil wrote:
    Implode wrote:
    if I want 3-34-565456-4 to be 334565456 so that I can take each digit and do calculations with them, could I just split the string 334565456 using .split(""); which will give me splitArray[0]=3, splitArray[1] = 3, splitArray[2] = 4 etc.
    String someStr = "3-34-565456-4";
    String numsOnly = someStr.replaceAll("-", ""); //or someStr.replaceAll("[^0-9]", "");
    for ( char c : numsOnly.toCharArray() ) {
    int digit = c - '0';
    }Or
    for ( int i = 0; i < numsOnly.length(); i++ ) {
    int digit = Integer.parseInt(numsOnly.substring(i, i+1));
    What is "digit" ? and doesn't it re-assign a new number to digit each iteration?
    Im not sure how I will access each digit.

  • Removing characters

    I need some help on removing characters from a string. The problem I am having is due to the fact the portion of the string I need to keep varies. A few examples are:
    1298-1011-1-842-10-0
    1298-1011-1-842-103-0
    1298-1011-1-842-1034-0
    1298-1011-1-842-10345-0
    I need only the fifth set of numbers (10,103,1034,10345) out of these id numbers. I guess I need a way to remove everything with a "-" from both the right and left of the fifth set of numbers. The left function works to remove the trailing two digits ("-0") off of each string. I am just having a problem figuring out how to strip out the rest when it varies. Any help would be appreciated.

    If you are using 10g you could use REGEXP_REPLACE. For example...
    create table test1 (col1 varchar2(50));
    insert into test1 values ('1298-1011-1-842-10-0');
    insert into test1 values ('1298-1011-1-842-103-0');
    insert into test1 values ('1298-1011-1-842-1034-0');
    insert into test1 values ('1298-1011-1-842-10345-0');
    create table test2 (c1 number, c2 varchar2(10));
    insert into test2 values (10, 'a');
    insert into test2 values (103, 'b');
    insert into test2 values (1034, 'c');
    insert into test2 values (10345, 'd');
    SQL> select regexp_replace(col1, '.*-.*-.*-.*-(.*)-.*', '\1') col5 from test1;
    COL5
    10
    103
    1034
    10345
    SQL> select t1.*, t2.* from test1 t1, test2 t2
      2  where regexp_replace(t1.col1, '.*-.*-.*-.*-(.*)-.*', '\1') = t2.c1;
    COL1                                                       C1 C2
    1298-1011-1-842-10-0                                       10 a
    1298-1011-1-842-103-0                                     103 b
    1298-1011-1-842-1034-0                                   1034 c
    1298-1011-1-842-10345-0                                 10345 d
    SQL> JR

  • Removing non english characters from my string input source

    Guys,
    I have problem where I need to remove all non english (Latin) characters from a string, what should be the right API to do this?
    One I'm using right now is:
    s.replaceAll("[^\\x00-\\x7F]", "");//s is a string having chinese characters.
    I'm looking for a standard Solution for such problems, where we deal with multiple lingual characters.
    TIA
    Nitin

    Nitin_tiwari wrote:
    I have a string which has Chinese as well as Japanese characters, and I only want to remove only Chinese characters.
    What's the best way to go about it?Oh, I see!
    Well, the problem here is that Strings don't have any information on the language. What you can get out of a String (provided you have the necessary data from the Unicode standard) is the script that is used.
    A script can be used for multiple languages (for example English and German use mostly the same script, even if there are a few characters that are only used in German).
    A language can use multiple scripts (for example Japanese uses Kanji, Hiragana and Katakana).
    And if I remember correctly, then Japanese and Chinese texts share some characters on the Unicode plane (I might be wrong, 'though, since I speak/write neither of those languages).
    These two facts make these kinds of detections hard to do. In some cases they are easy (separating latin-script texts from anything else) in others it may be much tougher or even impossible (Chinese/Japanese).

  • Removing non-alpha-numeric characters from a string

    How can I remove all non-alpha-numeric characters from a string? (i.e. only alpha-numerics should remain in the string).

    Or even without a loop ?
    Extract from the help for the Search and Replace String function :
    Right-click the Search and Replace String function and select Regular Expression from the shortcut menu to configure the function for advanced regular expression searches and partial match substitution in the replacement string.
    Extract from the for the advanced search options :
    [a-zA-Z0-9] matches any lowercase or uppercase letter or any digit. You also can use a character class to match any character not in a given set by adding a caret (^) to the beginning of the class. For example [^a-zA-Z0-9] matches any character that is not a lowercase or uppercase letter and also not a digit.
    Message Edité par JB le 05-06-2008 01:49 PM
    Attachments:
    Example_VI_BD4.png ‏2 KB

  • Removing characters from string after a certain point

    Im very new to java programming, so if this is a realy stupid question, please forgive me
    I want to remove all the characters in my string that are after a certain character, such as a backslash. eg: if i have string called "myString" and it contains this:
    109072\We Are The Champions\GEMINI
    205305\We Are The Champions\Queen
    4416\We Are The Champions\A Knight's Tale
    a00022723\We Are The Champions\GREEN DAYi would like to remove all the characters after the first slash (109072*\*We...) leaving the string as "109072"
    the main problem is that the number of characters before and after is not the always the same, and there is often letters in the string i want, so it cant be separated by removing all letters and leaving the numbers
    Is there any way that this can be done?
    Thanks in advance for all help.

    You must learn to use the Javadoc for the standard classes. You can download it or reference it on line. For example [http://java.sun.com/javase/6/docs/api/java/lang/String.html|http://java.sun.com/javase/6/docs/api/java/lang/String.html].

  • Removing Duplicate Characters in a String without using a Hashset

    I was wondering if anyone knew a way of removing duplicate characters in a string without using a Hashset.
    I want to go from
    helloworld -> helowrd

    okay, here it is
    1) use a loop, look through each character in the original string
    2) look at the new string, if this character exist, don't add it, otherwise add it.
    check out methods in java.lang.String

  • Removing \r\n from string

    Hello, how do I remove the "\r\n" newline characters from a
    string in AS3 ?
    I can do it in Flex using StringUtil trim, but that is not
    available in Flash.
    Thanks for any help.

    Try something like this which replaces returns with a space:
    //grep to globally (gi) look for returns
    var returns:RegExp=/\r/gi;
    //your input text
    var str:String="the text";
    //return the clean text
    str.replace(returns," ");

  • Trim last two characters of a String

    Hi,
    I have a task to trim the last two characters of a string in a column and get the rest as output for comparison purpose.
    the length of column value is not fixed.
    For example
    I/p O/p
    India_1 India
    America_2 America
    I achieved the result using the below query:
    SELECT SUBSTR (TRIM ('India_1'), 1, LENGTH (TRIM ('India_1')) - 2) FROM DUAL;
    I have used the trim function to remove the leading and trailing spaces in the column value.
    Could somebody please let me know if there is a better way to get the result .. like in one shot query.
    Thanks,
    Pratik

    I have a task to trim the last two characters of a string in a column
    SQL> with t as (
    select 'India_1' str from dual union all
    select 'America_2' from dual
    select regexp_replace(str, '..$') str1 from t
    STR1        
    India       
    America     
    2 rows selected.

  • Remove HTML tags from String

    it sounded prettty easy..
    I know the first part of my String is <html><center><p> and the last part is </p></center></html>
    but for saving it into the database I want to remove the HTML parts..
    I know how much characters the html stuff is.. I know what the html is.. how do I remove it from my string?

    If your String always starts with <html><center> and always ends with </center></html> you can use:
         int startLength = "<html><center>".length();
         int endLength = "</center></html>".length();
         String withoutHtml = myString.substring(startLength, myString.length() - endLength);

  • Remove part of a string

    Hey All Gurus,
    I have a string IEQUS94 I want to remove ieq from the string... how to do that?? Any thoughts!!
    Will reward point... for sure!
    Thanks Nina.

    There is a few ways to do this depending on some assumptions.
    Assumption 1,  that IEQ is always the first 3 characters.  If that is the case.....
    data: str type string.
    str = 'IEQUS94'.
    shift str left by 3 places.
    Regards,
    Rich Heilman

  • How to count number of repeated characters in a String

    I have a String.... 10022002202222.
    I need to know how many 2's are there in the string... here the string contains eight 2's..
    Thanks in advance..

    it is workingYes, but... attention to surprises...
    SQL> var v1 varchar2(1000);
    SQL> exec :v1 := 'How to count the number of occurences of a characters in a string';
    PL/SQL procedure successfully completed.
    SQL> select length(:v1) - length(replace(:v1,'c')) from dual;
    LENGTH(:V1)-LENGTH(REPLACE(:V1,'C'))
                                       6
    SQL> exec :v1 := 'cccccc';
    PL/SQL procedure successfully completed.
    SQL> select length(:v1) - length(replace(:v1,'c')) from dual;
    LENGTH(:V1)-LENGTH(REPLACE(:V1,'C'))
    SQL> select length(:v1) - nvl(length(replace(:v1,'c')),0) from dual;
    LENGTH(:V1)-NVL(LENGTH(REPLACE(:V1,'C')),0)
                                              6
    SQL>

Maybe you are looking for