Using CharAt for String Manipulation

Hi,
I am new to Java and am taking a Java class. I am trying to put a social security number in "nnn-nn-nnnn" format where n is a digit 0-9. I don't know if it would work with the charAt method of the String class. Does anyone have any suggestions on how to implement this kind of manipulation.
It would be greatly appreciated!
Thanks,
waggypup99

You could just create a class for social security number.
e.g.
public class SSNum{
    private int _num;
    public SSNum(int number){
      _num = number;
      * take number in the form  nnn-nn-nnnn
    public SSNum(String number){
      StringTokenizer st = new StringTokenizer(number,"-");
      StringBuffer numStringB = new StringBuffer(st.nextToken());
      numStringB.append(st.nextToken());
      numStringB.append(st.nectToken());
     _num = Integer.parseInt(numStringB.toString());
   public String toString(){
      //left as fun exercise
}

Similar Messages

  • A charAt() for Strings

    Since charAt() only works for chars, I was wondering if there is a method that does the same for Strings.
    Thanks in advance.

    Since charAt() only works for chars, I was wondering if there is a
    method that does the same for Strings.There's no such thing as a "chars". There's a single char such as 'A' and
    there's char arrays. The latter can be manipulated as any other type of
    array. And then there's the 'charAt()' method which incidentally is implemented
    by the String class.
    kind regards,
    Jos

  • Use Operator == for String Comparison

    Hi,
    I would like to know more about the impact of using operator == in String Comparison.
    From the reference I get, it state this :
    "Operator (==) compares two object addresses to see whether it refers to the same object."
    I've tested it with 2 codes as below :
    Code 1:
              String Pass1 = "cosmo";
              String Pass2 = "cosmo";          
    if (Pass1==Pass2)
                   System.out.println("1&2:same");
              else
                   System.out.println("1&2:not same");
    Output : 1&2:same
    Code 2:
              String Pass3 = new String("cosmo");
              String Pass4 = new String("cosmo");
              if (Pass3==Pass4)
                   System.out.println("3&4:same");
              else
                   System.out.println("3&4:not same");
    Output : 3&4:not same
    Can anyone kindly explain why is the result so? If operator == compares the addresses, isn't it that the 1st code should also have the output :"1&2:not same".

    Can anyone kindly explain why is the result so?It's an implementation artifact. Strings are pooled internally and because of that any String literal will be represented by exactly one object reference.
    Knowledge of this shouldn't be utilized though. It's safer to follow the basic rule: Use == to compare object references and equals to compare object values, such as String literals.

  • Using StartsWith for String Comparision in Business rules

    hi,
    I need to compare whether a particular string starts with some pre-defined prefixes. These are bound to change from time to time and hence we wanted to use the business rule engine for this. We declared prefixes using "list of values" vocab and
    defined the set. Now, I hoped to use the String.StartsWith() method but couldn't understand if it can be used.
    As of now, we are creating a method and that will be called with 2 parameters. One the string and other is one of the list of values which we want the string to start with. Is there any better way to do this?
    Praveen Behara
    MCST : BizTalk Server 2006 R2, 2010

    Hi Murugesan,
    I need to match a particular series of numbers... say 12xxx,345xxx,567xxx. I am creating a
    Series as a list and the valid values would be 12, 345, 567. I intend to keep them as prefixes i.e. they are not regular expressions. So, they won't be 12.*, 345.*, 567.*. The idea is to keep the vocab close to requirement
    and away from implementation (typically, for a business user). Now, if I want this setup, how will the implementation with
    Match look like?
    Technically, your above solution would work.. but my way of implementation / thought process is for a different purpose.
    Praveen Behara
    MCST : BizTalk Server 2006 R2, 2010

  • Using wildcards for String compare

    Hello,
    I want my prog to find out all Strings which start with the letters 'File'. How can I make a String compare by using wildcards ?
    Thanx,
    Findus

    You may use the String method startsWith to find strings beginning with File. eg. filename.startsWith("File")
    for more complicated comparisons you might want to use regular expressions.

  • Using concat for STrings

    I'm trying to concat a specified string, ".jpg", to a string of the form:
    filestring = afile.getName();
    filestring.concat(".jpg");
    Why does it not add the .jpg to the end of what filestring is?

    Cuz Strings are immutable dingbat. If you'd read the api you might notice concat returns a new string with the value you want, but you're chucking it since you didn't assign the result to a variable.
    Options:
    1) filestring = afile.getName() + ".jpg"
    2) filestring = afile.getName().concat(".jpg");
    3) filestring = afile.getName(); filestring = filestring.concat(".jpg");
    3) use StringBuffer instead

  • How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?

    Hi All,
    Hope to you a very happy new year,
    I have two differnt LAP 1300 and 1200 in my network and I need to add theme to the WLC,
    I successed to add one of theme by the option 60 in the DHCP pool at the Core SW,
    So my quetion is below:
    How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?
    Thanks in Advanced,
    Ahmed,

    To add to Scott's post.  Option 60 would be useful if you needed to put certain types of AP on specific controllers.  Otherwise, no real need to use it for the most part.
    Though, I do recall an issue a few years ago that some windows machines had issues getting DHCP if option 43 is being returned.
    Now, on an IOS switch, you can only configure one option 60 per DHCP scope
    HTH,
    Steve
    Please remember to rate useful posts, and mark questions as answered

  • Wat should be the regular expression for string MT940_UB_*.txt to be used in SFTP sender channel in PI 7.31 ??

    Hi All,
    What should be the regular expression for string MT940_UB_*.txt and MT940_MB_*.txt to be used as filename inSFTP sender channel in PI 7.31 ??
    If any one has any idea on this please let me know.
    Thanks
    Neha

    Hi All,
    None of the file names suggested is working.
    I have tried using - MT940_MB_*\.txt , MT940_MB_*.*txt , MT940*.txt
    None of them is able to pick this filename - MT940_MB_20142204060823_1.txt
    Currently I am using generic regular expression which picks all .txt files. - ([^\s]+(\.(txt))$)
    Let me know ur suggestion on this.
    Thanks
    Neha Verma

  • Using bytes or chars for String phonetic algorithm?

    Hi all. I'm working on a phonetic algorithm, much like Soundex.
    Basically the program receives a String, read it either char by char or by chunks of chars, and returns its phonetic version.
    The question is which method is better work on this, treating each String "letter" as a char or as a byte?
    For example, let's assume one of the rules is to remove every repeated character (e.g., "jagged" becomes "jaged"). Currently this is done as follows:
    public final String removeRepeated(String s){
                    char[] schar=s.toCharArray();
              StringBuffer sb =new StringBuffer();
              int lastIndex=s.length()-1;
              for(int i=0;i<lastIndex;i++){
                   if(schar!=schar[i+1]){
                        sb.append(schar[++i]);//due to increment it wont work for 3+ repetions e.g. jaggged -> jagged
              sb.append(schar[lastIndex]);
              return sb.toString();
    Would there be any improvement in this computation:public final String removeRepeated(String s){
              byte[] sbyte=s.getBytes();
              int lastIndex=s.length()-1;
              for(int i=0;i<lastIndex;i++){
                   if(sbyte[i]==sbyte[i+1]){
                        sbyte[++i]=32; //the " " String
              return new String(sbyte).replace(" ","");
    Well, in case there isn't much improvement from the short(16-bit) to the byte (8-bit) computation, I would very much appreciate if anyone could explain to me how a 32-bit/64-bit processor handles such kind of data so that it makes no difference to work with either short/byte in this case.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    You may already know that getBytes() converts the string to a byte array according to the system default encoding, so the result can be different depending on which platform you're running the code on. If the encoding happens to be UTF-8, a single character can be converted to a sequence of up to four bytes. You can specify a single-byte encoding like ISO-8859-1 using the getBytes(String) method, but then you're limited to using characters that can be handled by that encoding. As long as the text contains only ASCII characters you can get away with treating bytes and characters as interchangeable, but it could turn around and bite you later.
    Your purpose in using bytes is to make the program more efficient, but I don't think it's worth the effort. First, you'll be constantly converting between {color:#000080}byte{color}s and {color:#000080}char{color}s, which will wipe out much of your efficiency gain. Second, when you do comparisons and arithmetic on {color:#000080}byte{color}s, they tend to get promoted to {color:#000080}int{color}s, so you'll be constantly casting them back to {color:#000080}byte{color}s, but you have to watch for values changing as the JVM tries to preserve their signs.
    In short, converting the text to bytes is not going to do anywhere near enough good to justify the extra work it entails. I recommend you leave the text in the form of {color:#000080}char{color}s and concentrate on minimizing the number of passes you make over it.

  • Substring for Strings, what do I use for a int variable???

    Hi!
    substring for Strings...
    String s1 = p.substring(1,2);
    but what do I use for a int variable?
    int i1 = integ."???????"(1,2);
    /Henrik

    why, you use maths of course!!
    or if you're not up to that, try this:
    int x = 931;
    String s = x+"";
    String res = s.substring(1, 2);
    and of course set it back to an int
    with Integer.parseInt(res);

  • Using XDB for manipulating table BLOBS?

    Hi!
    I have got a database table with a BLOB column which contains MS Office documents.
    For editing the documents I have written a small application for downloading the document, edit it with Office and upload it again to the database. Can I use XDB for this task? If yes it would be easier to use because the users don't have to download and upload the documents...
    I would expect the following - when the user clicks for editing a document, I copy the blob-column to a temporary XDB directory (for example /public/editing). The document gets opened from the XDB directory (with file assosiation in the right office program) and the users edit and save the document directly to the XDB folder. When they have finished I update the table BLOB with the XDB file and remove the file from XDB.
    Can I use XDB therefore or do you know better solutions? I would be glad about any tips!
    Thanks
    Markus

    I assume that using the XML format for word documents is not an option... If is you register a dummy schema for WORD-ML (Don't try and register the complete schema) and then have a table level trigger to store the content back in your table.
    The problem is bi-directional..
    First, when the user wants to open a document how are you going to ensure that the 'virtual document' in the XML DB repository has the correct content. Even a trigger on XDB$RESOURCE cannot help here..
    Second, for writing the content back in theory a trigger on XDB$RESOURCE could work. However this is an unsupported confguration, since the trigger could slow down repository operation to the point where protocol timeouts could occur.
    The 11g XML DB repository events feature was designed to solve these problems...
    Message was edited by:
    mdrake

  • Why jvm maintains string pool only for string objects why not for other objects?

    why jvm maintains string pool only for string objects why not for other objects? why there is no pool for other objects? what is the specialty of string?

    rp0428 wrote:
    You might be aware of the fact that String is an immutable object, which means string object once created cannot be manipulated or modified. If we are going for such operation then we will be creating a new string out of that operation.
    It's a JVM design-time decision or rather better memory management. In programming it's quite a common case that we will define string with same values multiple times and having a pool to hold these data will be much efficient. Multiple references from program point/ refer to same object/ value.
    Please refer these links
    What is Java String Pool? | JournalDev
    Why String is Immutable in Java ? | Javalobby
    Sorry but you are spreading FALSE information. Also, that first article is WRONG - just as OP was wrong.
    This is NO SUCH THING as a 'string pool' in Java. There is a CONSTANT pool and that pool can include STRING CONSTANTS.
    It has NOTHING to do with immutability - it has to do with CONSTANTS.
    Just because a string is immutable does NOT mean it is a CONSTANT. And just because two strings have the exact same sequence of characters does NOT mean they use values from the constant pool.
    On the other hand class String offers the .intern() method to ensure that there is only one instance of class String for a certain sequence of characters, and the JVM calls it implicitly for literal strings and compile time string concatination results.
    Chapter 3. Lexical Structure
    In that sense the OPs question is valid, although the OP uses wrong wording.
    And the question is: what makes class Strings special so that it offers interning while other basic types don't.
    I don't know the answer.
    But in my opinion this is because of the hybrid nature of strings.
    In Java we have primitive types (int, float, double...) and Object types (Integer, Float, Double).
    The primitive types are consessons to C developers. Without primitive types you could not write simple equiations or comparisons (a = 2+3; if (a==5) ...). [autoboxing has not been there from the beginning...]
    The String class is different, almost something of both. You create String literals as you do with primitives (String a = "aString") and you can concatinate strings with the '+' operator. Nevertheless each string is an object.
    It should be common knowledge that strings should not be compared with '==' but because of the interning functionality this works surprisingly often.
    Since strings are so easy to create and each string is an object the lack ot the interning functionality would cause heavy memory consumption. Just look at your code how often you use the same string literal within your program.
    The memory problem is less important for other object types. Either because you create less equal objects of them or the benefit of pointing to the same object is less (eg. because the memory foot print of the individual objects is almost the same as the memory footpint of the references to it needed anyway).
    These are my personal thoughts.
    Hope this helps.
    bye
    TPD

  • Trying to use charAt()

    I've got a file with full firstnames and lastnames and I'm trying to print out the initials of the first names and then the last name in full but I got stuck. Whenever I try to compile the code I get "cannot resolve symbol / name1 += str.charAt( 0 );" with a ^ under the dot operator
    public String names ( String name )
                 StringTokenizer str = new StringTokenizer ( name );
              int x = 0;
              int y = 0;
              String name1;
              x = str.countTokens();
              for ( int a = 0; a < x; a++ )
                   if ( a != ( y-1))
                        name1 += str.charAt( 0 );
                        name1 += " ";
                   else
                        name1 += str;
             return name1;
        }some help would be very much appreciated

    I prefer to show you a smart and fast solution...not the best:
    public String names(String name)
      // avoid mal function due to bad argument
      if (name==null || name.length()==0) return null;
      // the best practice is to use StringBuffer
      // since String objects are immutable
      StringBuffer result = new StringBuffer();
      StringTokenizer str = new StringTokenizer ( name );
      for (int j=str.countTokens(); j>1; j--)
        result.append( str.nextToken().charAt(0) ).append(" ");
      result.append(str.nextToken()); // append whole last token
      return result.toString();
    }

  • Using toString for substring of integer

    First post. New to OOP and in my first week of learning Java. Playing around with different class/methods and functions in the API, trying to get a feel for implemetation in code.
    Let's say I want to get the length of int iNumber and put it in int iLength. I know I can do this:
    iLength = Integer.toString(iNumber).length();
    Where Integer.toString(iNumber) creates the string object and then I can invoke the string length method.
    Expanding on that, I'm trying to figure out why the compiler is complaining about "incompatible types" on this one (where strTemp is char):
    strTemp = Integer.toString(iNumber).substring(1,1);
    as well as this, where iTemp is integer:
    iTemp = Integer.toString(iNumber).substring(1,1);
    Again, total newbie, so apologies if I'm missing something obvious.

    Or you could have daisy-chained another method.
    strTemp = Integer.toString(iNumber).substring(1,1).charAt(0);Or use charAt directly.
    strTemp = Integer.toString(iNumber).charAt(0);Also, you should read the API for the substring method and what the parameters do. (1,1) will not produce the results you were expecting.

  • I use Outlook for my email on the Safari web browser, and about 90% of the time when I want to attach a pdf or jpg file the email message will crash.

    I use Outlook for my email on the Safari web browser, and about 90% of the time when I want to attach a pdf or jpg file it fails and about 50% of the time when I want to send a standard text massage it will also fail and the email massage crashes. The only way I can get my Outlook to work is if I switch to Firefox web browser. I would rather not switch to a new web browser if I don't have to.
    It seems like what ever the problem is that its related the Safari web browser, because it works fine on the Firefox web browser.
    I think its some kind of plug-in failure because it giving me a LOC ERROR:
    LOC ERROR: Unable to locate localized string for resource ID 5007.
    How can I fix this Plug-in?
    And, yes my softwer is conpletly updated…

    That's an Outlook issue. You'll probably get better responses posting on the Office for Mac forums.

Maybe you are looking for