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
}

Similar Messages

  • 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);

  • 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

  • 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.

  • Removing Non-Ascii Characters from a String

    Hi Everyone,
    I would like to remove all NON-ASCII characters from a large string. For example, I am taking text from websites and would like to remove all the strange arabic and asian characters. How can I accomplish this?
    Thank you in advance.

    I would like to remove all NON-ASCII characters from a large string. I don't know if its a good method but try this:
    str="\u6789gj";
    output="";
    for(char c:str.toCharArray()){
         if((c&(char)0xff00)==0){
              output=output+c;
    System.out.println(output);
    all the strange arabic and asian characters.Don't call them so.... I am an Indian Muslim ;-) ....
    Thanks!

  • Removing unwanted characters from imported string

    Hello,
    I have a tab-delimited .txt file which I have to import into Indesign for further processing.
    The file is composed by a 3 columns header row at the beginning (Code, Description, price) followed by a series of 3 columns data rows.
    The problem is that sometimes, depending on the way the txt/csv file has been created, may include unwanted characters (such as spaces, double spaces, etc.).
    Is there a way to "clean" the imported strings from these unwanted characters?
    This is my starting code:
    function processImportedTxt(){
        //Open .csv file
        var csvFile = File.openDialog("Open file .csv","tab-delimited(*.csv):*.csv;");
        datafile = new File(csvFile);
        if (datafile.exists){
            datafile.open('r');
       var csvData = new Array();
       while(!datafile.eof){//read every row till the end of file
            csvData.push(datafile.readln());
        datafile.close();
        for(a=1; a<csvData.length; a++){
            var myRowData = csvData[a];//row of data
            var mySplitData = myRowData.toString().split("\t");//divide columns
            var myRowCode = mySplitData[0];
            var myRowDesc = mySplitData[1];
            var myRowPrice = mySplitData[2];
            // Here goes code for cleaning strings from unwanted characters
    processImportedTxt();
    Any help would be much appreciated
    Thanks in advance

    Hi,
    If you want to safe 1-space occurences just a small correction:
    i.e.:
    var myRowCode = mySplitData[0].replace(/\s\s+/g,'');
    Jarek

  • Remove all non-number characters from a string

    hi
    How i can remove all non-number characters from a column ? for example , i have a column that contains data like
    'sd3456'
    'gfg87s989'
    '45/45fgfg'
    '4354-df4456'
    and i want to convert it to
    '3456'
    '87989'
    '4545'
    '43544456'
    thx in adv

    Or in 9i,
    Something like this ->
    satyaki>
    satyaki>with vat
      2  as
      3    (
      4      select 'sd3456' cola from dual
      5      union all
      6      select 'gfg87s989' from dual
      7      union all
      8      select '45/45fgfg' from dual
      9      union all
    10      select '4354-df4456' from dual
    11    )
    12  select translate(cola,'abcdefghijklmnopqrstuvwxyz-/*#$%^&@()/?,<>;:{}[]|\`"',' ') res
    13  from vat;
    RES
    3456
    87989
    4545
    43544456
    Elapsed: 00:00:00.00
    satyaki>
    {code}
    I checked this with minimum test cases. It will be better if you checked it with other cases.
    Regards.
    Satyaki De.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • 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].

  • How can I remove all non alpha/space characters from a string

    Subject changed by moderator.  Please use a meaningful subject in future.
    Hi all,
    Can anyone tell me.
    how to get only alphabets & spaces from the string..
    suppose..
    raj*&{]afhajk ajkf_+#fkh jah jka7767jk hhha
    I need only
    rajafhajk ajkf fkh jah jkajk hhha
    thanks..
    Rajeev
    Edited by: Matt on Feb 17, 2009 3:36 PM

    This will work.
    CONSTANTS:
      sm2big(52) VALUE
        'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'.
    DATA:
      str_out(60),
      str_in(60) VALUE
      'raj*&{]afhajk ajkf_+^#^fkh jah jka7767jk hhha',
      my_len          TYPE i,
      pos1            TYPE i,
      pos2            TYPE i.
    START-OF-SELECTION.
      COMPUTE my_len = strlen( str_in ).
      CLEAR pos1.
      CLEAR pos2.
      WHILE pos1 LT my_len.
        IF str_in+pos1(1) co sm2big
        OR str_in+pos1(1) EQ ' '.
          str_out+pos2(1) = str_in+pos1(1).
          pos2 = pos2 + 1.
        ENDIF.
        pos1 = pos1 + 1.
      ENDWHILE.
      WRITE:/ 'String In', str_in.
      WRITE:/ 'String Out', str_out.
    and the output
    String In      raj*&{]afhajk ajkf_+^#^fkh jah jka7767jk hhha
    String Out   rajafhajk ajkffkh jah jkajk hhha            

  • Replacing a set of characters from a string in oracle sql query

    I want to replace a set of characters ( ~    !     @    #     $     %     ^     *     /     \     +    :    ;    |     <     >     ?    _  ,) from a STRING in sql
    select 'TESTING ! ABC 123 #'
    FROM DUAL;
    What is the best way to do it? Please provide examples also.

    What is your expected output... The query I posted just removes them, it never replaces them with spaces..your string already has space.. if you want to remove space as well .. try this...
    SELECT TRANSLATE ('TESTING ! ABC 123 #', '-~!@#$%^*/\+:;|<>?_, ', ' ') FROM DUAL;
    Output:
    --TESTINGABC123
    Else post your expected output..
    Cheers,
    Manik.

  • 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 from an input data-field

    Hi.
    Is it possible to "Trim Off" characters from a Text Field data, and automatically input them into another Text field?
    Let's say I have the following code :
    *<Field name='telephonenumber'>*
    *<Display class='Text'>*
    *<Property name='title' value='Phone Number in International Format'/>*
    *<Display>*
    *</Field>*
    This code is to input the telephone number in International Format (such as :  +1 234 567 8900)
    Now, lets say that I want to create a second Data Text field for phone number; but, this time, it is for the phone number in LOCAL format.
    In other words, I want to write a code which will AUTOMATICALLY  remove the first 3 or 4 characters from the "International Number",  and input them into the "Local Number"  field.
    This would save me the trouble or writing the number a second time. My code should be able to simply Trim Off the initial "+1 234", and automatically input the remaining "*567 8900"* into the Local Number field.
    How could I accomplish this?
    Thanks

    Based on your code, it looks like you have fields called global.workgsmad (local style) and global.workgsm (international style)
    Assuming your global.workgsm format will always be '+x xxx xxx xxxx' you want to skip the first 6 characters, not 4
    The simplest way to do this is like so:
    <Field name='global.workgsmad'>
       <Expansion>
          <substr>
             <ref>global.workgsm</ref>
             <i>6</i>     <!-- Skip the country code and area code '+x xxx ' -->
             <i>8</i>   <!-- 8 characters were left for the format 'xxx xxxx' -->
          </substr>
       </Expansion>
    </Field>Alternatively, you could change the substr block to read
    <substr s='6' l='8'>
       <ref>global.workgsm</ref>
    </substr>Both formats are valid.
    If the phone number is not a fixed format, you'll have to do something more complicated.
    Jason

  • Can't get an array of characters from a string!

    If I have a string eg "Hello World", how do I get an array containing the characters eg. [H,e,l,l,o, ,W,o,r,l,d]
    Can any one help me please?

    Or to get the chars you want from a String object you can do this:
    String helloString = new String("Hello World");
    char[] helloArray = helloString.toCharArray();

Maybe you are looking for

  • How to increase the size of acquisition window in C++ code

    Hi, I am using PCI 1405 to continuously acquire video images from vcr playback. I tried to make use of the OnGrab function provided in the sample files, and included this function into my C++ application, without using LabView. However I have difficu

  • Network Connection To Store Timed Out???  Advise Extremely Appreciated!

    Hi everyone, I am/was thinking about buying an iPod Touch for myself and I thought I'd go ahead and get iTunes. I see everyone is having this problem, but I am in need of personal advise. Here are the diagnostics: Microsoft Windows XP Professional Se

  • Is it possible to centre a JFrame title?

    So that the titlebar for it has "ApplicationName" centred rather than left-justified? Thanks.

  • HP mini 110 Can't factory reset

    I am trying to do a factory restore on my netbook. Using the older XP operating software, this is not an option as I can only back up to restore points. Please advise on how I can get this done.

  • Locokpit

    hi, i have some doubts regardsing locokpit. actually i want to uploading 2lis_11_vahdr. i went to to lbwe .i selected the maintstrucure and i selected data source , deleted the datasou8rce . when i  go to initilization. i getting some error is no ext