Chars - subString - String

Good morning...
I got a sub sequence of a string... n now I'm trying to use this sub string as a string... but the javac only tells me a warning like incompatible types...
inputLine.subSequence(tamanho-contador,tamanho-(contador-5))
I tryed to convert that charSequence (that java says me) and convert to a string.. but it brings me that java.lang.Object cannot be applied to java.lang.charSequence
How may I do to take that substring n use like another independent string?
I would like to put more three chars before convert it.
Like:
abc123def
I took c123d using subSequence n I want to put more three chars "jav" to finally my string stay like c123djav
How may I do to put more chars n convert it to a String? (In start I was suposed that the substring was a string... but it makes me an error....)
Thanks...

Ok... I used that
String anT = inStr.substring(inStr.indexOf('c'), inStr.length()-2)+"jav";
But it makes a warning like:
subSequence(int,int) in java.lang.String cannot be applied to (int, java.lang.String)
I think I need to mix the "jav" after take the string... c123d ... but even only taking that subSequence, and trying to put in a string, I have a warning like:
incompatible types
found: java.lang.charSequence
required: java.lang.String

Similar Messages

  • Replace char on String

    Hi All,
    String strValue = "ABC TPT 0694";
    My String is as shown above, I am looking for a way to replace char at byte 6 (position 6) with another Char in String.
    For example at location 6 it is "T" I want to replace it with char "O". can any one tell me how to do this

    String strValue = "ABC TPT 0694";
    char[] chars = strValue.toCharArray();
    chars[5] = 'O';
    strValue = String.valueOf(chars);

  • What api would I use to get the number of chars in string?

    What api would I use to get the number of chars in string?

    Assuming that you really mean that you want the number of charaters in a String (not string), that would be documented in java.lang.String
    The method is length()

  • ASCII character/string processing and performance - char[] versus String?

    Hello everyone
    I am relative novice to Java, I have procedural C programming background.
    I am reading many very large (many GB) comma/double-quote separated ASCII CSV text files and performing various kinds of pre-processing on them, prior to loading into the database.
    I am using Java7 (the latest) and using NIO.2.
    The IO performance is fine.
    My question is regarding performance of using char[i] arrays versus Strings and StringBuilder classes using charAt() methods.
    I read a file, one line/record at a time and then I process it. The regex is not an option (too slow and can not handle all cases I need to cover).
    I noticed that accessing a single character of a given String (or StringBuilder too) class using String.charAt(i) methods is several times (5 times+?) slower than referring to a char of an array with index.
    My question: is this correct observation re charAt() versus char[i] performance difference or am I doing something wrong in case of a String class?
    What is the best way (performance) to process character strings inside Java if I need to process them one character at a time ?
    Is there another approach that I should consider?
    Many thanks in advance

    >
    Once I took that String.length() method out of the 'for loop' and used integer length local variable, as you have in your code, the performance is very close between array of char and String charAt() approaches.
    >
    You are still worrying about something that is irrevelant in the greater scheme of things.
    It doesn't matter how fast the CPU processing of the data is if it is faster than you can write the data to the sink. The process is:
    1. read data into memory
    2. manipulate that data
    3. write data to a sink (database, file, network)
    The reading and writing of the data are going to be tens of thousands of times slower than any CPU you will be using. That read/write part of the process is the limiting factor of your throughput; not the CPU manipulation of step #2.
    Step #2 can only go as fast as steps #1 and #3 permit.
    Like I said above:
    >
    The best 'file to database' performance you could hope to achieve would be loading simple, 'known to be clean', record of a file into ONE table column defined, perhaps, as VARCHAR2(1000); that is, with NO processing of the record at all to determine column boundaries.
    That performance would be the standard you would measure all others against and would typically be in the hundreds of thousands or millions of records per minute.
    What you would find is that you can perform one heck of a lot of processing on each record without slowing that 'read and load' process down at all.
    >
    Regardless of the sink (DB, file, network) when you are designing data transport services you need to identify the 'slowest' parts. Those are the 'weak links' in the data chain. Once you have identified and tuned those parts the performance of any other step merely needs to be 'slightly' better to avoid becoming a bottleneck.
    That CPU part for step #2 is only rarely, if every the problem. Don't even consider it for specialized tuning until you demonstrate that it is needed.
    Besides, if your code is properly designed and modularized you should be able to 'plug n play' different parse and transform components after the framework is complete and in the performance test stage.
    >
    The only thing that is fixed is that all input files are ASCII (not Unicode) characters in range of 'space' to '~' (decimal 32-126) or common control characters like CR,LF,etc.
    >
    Then you could use byte arrays and byte processing to determine the record boundaries even if you then use String processing for the rest of the manipulation.
    That is what my framework does. You define the character set of the file and a 'set' of allowable record delimiters as Strings in that character set. There can be multiple possible record delimiters and each one can be multi-character (e.g. you can use 'XyZ' if you want.
    The delimiter set is converted to byte arrays and the file is read using RandomAccessFile and double-buffering and a multiple mark/reset functionality. The buffers are then searched for one of the delimiter byte arrays and the location of the delimiter is saved. The resulting byte array is then saved as a 'physical record'.
    Those 'physical records' are then processed to create 'logical records'. The distinction is due to possible embedded record delimiters as you mentioned. One logical record might appear as two physical records if a field has an embedded record delimiter. That is resolved easily since each logical record in the file MUST have the same number of fields.
    So a record with an embedded delimiter will have few fields than required meaning it needs to be combined with one, or more of the following records.
    >
    My files have no metadata, some are comma delimited and some comma and double quote delimited together, to protect the embedded commas inside columns.
    >
    I didn't mean the files themselves needed to contain metadata. I just meant that YOU need to know what metadata to use. For example you need to know that there should ultimately be 10 fields for each record. The file itself may have fewer physical fields due to TRAILING NULLCOS whereby all consecutive NULL fields at the of a record do not need to be present.
    >
    The number of columns in a file is variable and each line in any one file can have a different number of columns. Ragged columns.
    There may be repeated null columns in any like ,,, or "","","" or any combination of the above.
    There may also be spaces between delimiters.
    The files may be UNIX/Linux terminated or Windows Server terminated (CR/LF or CR or LF).
    >
    All of those are basic requirements and none of them present any real issue or problem.
    >
    To make it even harder, there may be embedded LF characters inside the double quoted columns too, which need to be caught and weeded out.
    >
    That only makes it 'harder' in the sense that virtually NONE of the standard software available for processing delimited files take that into account. There have been some attempts (you can find them on the net) for using various 'escaping' techniques to escape those characters where they occur but none of them ever caught on and I have never found any in widespread use.
    The main reason for that is that the software used to create the files to begin with isn't written to ADD the escape characters but is written on the assumption that they won't be needed.
    That read/write for 'escaped' files has to be done in pairs. You need a writer that can write escapes and a matching reader to read them.
    Even the latest version of Informatica and DataStage cannot export a simple one column table that contains an embedded record delimiter and read it back properly. Those tools simply have NO functionality to let you even TRY to detect that embedded delimiters exist let alone do any about it by escaping those characters. I gave up back in the '90s trying to convince the Informatica folk to add that functionality to their tool. It would be simple to do.
    >
    Some numeric columns will also need processing to handle currency signs and numeric formats that are not valid for the database inpu.
    It does not feel like a job for RegEx (I want to be able to maintain the code and complex Regex is often 'write-only' code that a 9200bpm modem would be proud of!) and I don't think PL/SQL will be any faster or easier than Java for this sort of character based work.
    >
    Actually for 'validating' that a string of characters conforms (or not) to a particular format is an excellent application of regular expressions. Though, as you suggest, the actual parsing of a valid string to extract the data is not well-suited for RegEx. That is more appropriate for a custom format class that implements the proper business rules.
    You are correct that PL/SQL is NOT the language to use for such string parsing. However, Oracle does support Java stored procedures so that could be done in the database. I would only recommend pursuing that approach if you were already needing to perform some substantial data validation or processing the DB to begin with.
    >
    I have no control over format of the incoming files, they are coming from all sorts of legacy systems, many from IBM mainframes or AS/400 series, for example. Others from Solaris and Windows.
    >
    Not a problem. You just need to know what the format is so you can parse it properly.
    >
    Some files will be small, some many GB in size.
    >
    Not really relevant except as it relates to the need to SINK the data at some point. The larger the amount of SOURCE data the sooner you need to SINK it to make room for the rest.
    Unfortunately, the very nature of delimited data with varying record lengths and possible embedded delimiters means that you can't really chunk the file to support parallel read operations effectively.
    You need to focus on designing the proper architecture to create a modular framework of readers, writers, parsers, formatters, etc. Your concern with details about String versus Array are way premature at best.
    My framework has been doing what you are proposing and has been in use for over 20 years by three different major nternational clients. I have never had any issues with the level of detail you have asked about in this thread.
    Throughout is limited by the performance of the SOURCE and the SINK. The processing in-between has NEVER been an issu.
    A modular framework allows you to fine-tune or even replace a component at any time with just 'plug n play'. That is what Interfaces are all about. Any code you write for a parser should be based on an interface contract. That allows you to write the initial code using the simplest possible method and then later if, and ONLY if, that particular module becomes a bottlenect, replace that module with one that is more performant.
    Your intital code should ONLY use standard well-established constructs until there is a demonstrated need for something else. For your use case that means String processing, not byte arrays (except for detecting record boundaries).

  • Delete a char from string ?

    Hi,
    I want to delete a char from string. i used the following function.
    String f = formulla.replace('[','');
    The above function doesnt work as it tells me to put a space or some char in 2nd parameter which i dont want. i just want to delete all occurences of some specific char in a string.
    Any suggestion.
    Thanks alot.

    u can do:
    String before;
    char charToReplace;
    StringBuffer tempBuf = new StringBuffer(before);
    for (int i=0; i<tempBuf.length(); i++)
            if (tempBuf.charAt(i)==charToReplace)
                  tempBuf.deleteCharAt(i);
    String after = tempBuf .toString(); HTH
    Yonatan

  • I have to generate a 4 char unique string from a long value

    I got a requirment
    I have to generate a 4 char unique string from a long value
    Eeach char can be any of 32 character defined has below.
    private static final char char_map[] = new char[]{'7','2','6','9','5','3','4','8','X','M','G','D','A','E','B','F','C','Q','J','Y','H','U','W','V','S','K','R','L','N','P','Z','T'};
    So for 4 char string the possible combination can be 32 * 32 * 32 * 32 = 1048576
    If any one passes a long value between 0 - 1048576 , it should generate a unique 4 char string.
    Any one with idea will be a great help.

    Well, a long is 64 bits. A char is 16 bits. Once you determine how you want to map the long's bits to your char bits, go google for "java bitwise operators".

  • Converting chars to strings

    I don't know how to get this thing to work:
    public class TestGrade
    public static void main(String[] args)throws GradeException
      int studentID = 123423;
      char grade;
      String aGrade = new String();
      try
       System.out.println("Student #: " + studentID);
       System.out.println("Enter a letter grade for student: ");
       grade = (char)System.in.read();
       if(grade >= 'A' && grade <= 'F' || grade >= 'f' && grade <= 'f')
        System.out.println("Student ID#: " + studentID + "Grade: " + grade);
        aGrade = grade;
       else
        throw(new GradeException(aGrade));
      catch(GradeException error)
           System.out.println("Test Error: " + error.getMessage ());
    }

    it might help if I tell you where the error is...
       aGrade = grade; generates a rather obvious error. Incompatible types, I don't know how to convert this sucker into a string so I can feed a string into GradeException....

  • Get chars from string of numerals

    here is what I would like to accomplish:
    Put the last four integers of the systemDate into a variable so I can do some math with them.
    Thanks.

    Excellent.  Thank you for the info.  Very helpful.
    Dewey
    From: jchunick [email protected]
    Sent: Friday, June 03, 2011 4:20 PM
    To: Dewey Parker
    Subject: Re: get chars from string of numerals
    This is a post I made for the wiki which should help: http://director-online.com/dougwiki/index.php?title=Undocumented_Lingo#the_systemDate

  • Replacing chars in strings

    Here is the situation:
    int x=4
    char letter1='Z'
    String word1="blah blah"
    /code]
    I was wonering if the was an easy way of replacing a character in a string with another at a ceratin point in the string. In this case, I want a string that would say "blahZblah". Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Sure
    int x=4
    char letter1='Z'
    String word1="blah blah"
    [String word2 = word1.substring(0,x) + letter1 + word.substring(x + 1)[/b]

  • Remove last char of string

    Hi Guys
    How can I remove the last char of a String ?

    With [the substring method|http://java.sun.com/javase/6/docs/api/java/lang/String.html#substring(int,%20int)] .

  • Parsing char[] to String

    I am trying to parse a char[]. Everytime I find a '\n' character I want to take the offset to that position and create a String from it. It doesn't seem to work like expected.. The strings contain parts of the array that shouldn't be there. here is some sample code that I am using. Let me know if anyone has any suggestions..
    Thanks
    public void parseArray( char[] buf ){
    int offset = 0;
    Vector v = new Vector();
    for( int i=0; i < buf.length; i++ ){
    if ( buf[ i ] == '\n' ){
    v.add( new String( buf, offset, i ) );
    offset = (i +1);
    }

    Try:
         public Vector parseArray(char buf[]) {
              Vector v = new Vector();
              String s = new String(buf);
              int offset =0, pos;
              do {
                   pos = s.indexOf('\n',offset);
                   if (pos != -1) {
                        String sub = s.substring(offset, pos);
                        v.add(sub);
                        offset = pos+1;
              } while (pos != -1 && offset < buf.length);
              if (offset < buf.length)
                   v.add(s.substring(offset));
              return v;
         }

  • How can I erase the last char of string

    I have a string tha is printing as following
    129.111.13.1.
    I want to erase the last "." can somebody helpme?
    Thanks

    You will have to create a new String. Then you can get the string length. Then you will need to to use a substring to get the positions you want.
    Something like this
    String Orginal = "129.111.13.1.";
    String new_orginal = null;
    int num;
    num = Original.length();
    new_orginal = Original.substring(0,num-1);
    I hope it helps

  • Convert char[] to string

    Hi,
    How can I convert a char array to string?

    Don't worry about it.
    Just I have to use String(char[])
    Thanks :)

  • How can i convert a char[] to String?

    Hi all!,
    What would be the easiest way to convert a char[] to a String? Im trying to set the text of a JTextArea which takes a String as an arguement but i have a character arry that if filled from a FileReader. Any suggestions?
    Thanks.

    The easiest way would be new String(charArray). There's a version of the constructor in the String class that take a char array

  • Validating Char. & Strings

    Hello,
    I am a novice programmer and my program does not check for strings and numeric characters. Below is my program, please give me some feedback, as soon as possible. Thanks a lot
    Martin
    import javax.swing.JOptionPane;
    import java.text.DecimalFormat;
    public class GradeWatch6{//start of class definition GradeWatch
         public static void main ( String args[] ) {//start of main method
              //string declarations
              String firstname="";
              String secondname;
              String studentid;
              String midtermgrade;
              String finalgrade;
              String listings="";
              String option;//variable used to receive user's option <-1>//<0>
              //character declarations
              char actualgrade;//letter grade assigned to total points earned
              char lettergrade=0;//assignment of a letter grade
              //integer declarations
              int loop=0;//(this will be converted fr. option//will compare result)
              int studentid_int;
              int midterm_grade=0;
              int final_grade=0;
              double midterm_gradevalue=0;//point calculations
              double final_gradevalue=0;//point calculations
              double total_gradevalue=0;//total points possible out of 100
              do
              //input dialogs (5)
              boolean firstnamecheck=true;
              while (firstnamecheck=false){
              firstname = JOptionPane.showInputDialog("Enter The Student's First Name: ");
              if (!Character.isLetter(firstname.charAt(0)))
                   firstnamecheck=false;
              for (int j=1;j<firstname.length();j++)
                   if (!Character.isDigit(firstname.charAt(j)))
                             firstnamecheck=false;
                             System.out.println(""+firstnamecheck);//printing on black screen
                             secondname= JOptionPane.showInputDialog ( "Invalid Entry!" );
              secondname = JOptionPane.showInputDialog("Enter The Student's Last Name: ");
              studentid = JOptionPane.showInputDialog("Student Id is the Student's Social Security Number.\nEnter The Student's ID #: ");
              studentid_int= Integer.parseInt(studentid);
              /*Validates student id so that it can only receive a 9 digit number,
              no negative values, and only alows integer input/
              while ( (studentid.length()!=9) ||(studentid_int<0) )
                        studentid= JOptionPane.showInputDialog ( "Invalid Entry! \n Student Id is the Student's Social Security Number.\nPlease Re-Enter Student Id: ");
                        studentid_int= Integer.parseInt(studentid);
              midtermgrade = JOptionPane.showInputDialog("This is worth 40% of Student's Grade.\nEnter Mid-term Grade: ");
              midterm_grade = Integer.parseInt( midtermgrade);
              while ( (midterm_grade < 0) || (midterm_grade > 100) )
                        midtermgrade=JOptionPane.showInputDialog ("Invalid Entry!\nA grade entered must be between (0-100).\nPleae Re-Enter Mid-term Grade: ");
                        midterm_grade = Integer.parseInt( midtermgrade);
              finalgrade = JOptionPane.showInputDialog("This is worth 60% of Student's Grade.\nEnter Final Grade:");
              final_grade= Integer.parseInt( finalgrade);
              while ( (final_grade<0) || (final_grade > 100) )
                        finalgrade= JOptionPane.showInputDialog ("Invalid Entry!\nA grade entered must be between (0-100).\nPleae Re-Enter the Final's Grade: ");
                        final_grade= Integer.parseInt( finalgrade);
              DecimalFormat twoDigits = new DecimalFormat( "0.00");
              //calculations for grades
                   //midterm is worth 40% of grade
              midterm_gradevalue = midterm_grade * .4;
                   //final is worth 60% of grade
              final_gradevalue = final_grade * .6;
                   //calculates the final grade for the student in class
              total_gradevalue = midterm_gradevalue + final_gradevalue;
              //if else statement for grade allotment
              if (total_gradevalue>=90)
                   lettergrade='A';
              else if (total_gradevalue>=80)
                   lettergrade='B';
              else if (total_gradevalue>=70)
                   lettergrade='C';     
              else if (total_gradevalue>=60)
                   lettergrade='D';     
              else if (total_gradevalue>=50)
                   lettergrade='F';          
              //Shows Output of Information Entered (5) of one student               
              JOptionPane.showMessageDialog
                   (null, "Student: " + secondname + " , " + firstname +
                        "\nMid-Term Points Earned: " + midterm_gradevalue +
                        "\nFinal Points Earned: " + final_gradevalue +
                        "\nTotal Points Earned: " + total_gradevalue +
                        "\nGrade Assigned: "+ lettergrade,
                        "\n STUDENT ID #: " + studentid,
                        JOptionPane.PLAIN_MESSAGE);
              /*Askes user whether or not to input an additional student*/
              option = JOptionPane.showInputDialog("Enter < 0 > to input a student. \nEnter < -1 > to quit. ");
              //converts string input into integer loop     
              loop = Integer.parseInt( option );
         listings +="Student ID #: " + studentid +
                   "\n [ " + secondname + ", " + firstname + " ] " +
                   "\n Midterm Points Earned: " + midterm_gradevalue +
                   "\n Final Points Earned: " + final_gradevalue +
                   "\n Total Points Earned: " + total_gradevalue +
                   "\n**********Grade Assigned: "+ lettergrade + "\n";
              } while ( loop !=-1);     
              JOptionPane.showMessageDialog(
                   null, listings,
                   "Class Results: ",
                   JOptionPane.PLAIN_MESSAGE);
              System.exit ( 0 );
         }//end of programming method
    }//end of class definition

    You didn't indent your code, so that makes it hard to read, and there's a lot of it that has nothing to do with what your question might be. But you want feedback? Well you are "validating" the student's first name in a strange way. A letter followed by any characters that aren't digits -- for example, "a++?" would pass. And that validation will fail if an empty string is provided, because "charAt(0)" assumes there is at least one character. I would just check it isn't blank. And I would provide a meaningful error message. "Invalid Entry" is unhelpful as it doesn't tell the user what is wrong with the input.

Maybe you are looking for

  • How to decrease width of the dropdown bookmark panel (FF 11)?

    How to decrease width of the dropdown bookmark panel (FF 11)? This panel is too wide and covers too much space in underlying windows. The book marks text should not be truncated but some way needs to be found to allow the entire text of any line to b

  • Error in MIGO with over delivery tolerance

    Hi Team, In material master using purchasing value key we have set 10% over & under delivery tolerance limit.i have created a PO with 10 qty and when i try to increase the qty to 11 in MIGO i am getting the error message "PO ordered qty exceed by 1",

  • N73 + Jabra BT620s, playing quality

    Nokia n73 (RM-133), FW v4.0839.42.0.1 Jabra BT620s, FW v1-31-0 (latest) Problem: Jabra BT620s - is stereo bluetooth headphones. When playing music there is periodically tone deviation - i.e. speed of playing can be faster then normal, or can be slowe

  • How do you join .001 files in OS X?

    Hi, I have several files (mp3) in the .001 format, and I was wondering if there was any application available to join these files in OS X. These are split, not compressed files. From what I gathered, in Windows, they commonly use WinRAR or 7-Zip, but

  • Change actionListener binding #{bindings.ExecuteWithParams} to other

    Hi, What i want to do is change a button ActionListener binding from *#{bindings.ExecuteWithParams.execute}* to *#{bindings.ExecuteWithParams1.execute}* at run time For this a method setActionListener() in CoreCommandButton is given but when i do thi