• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

substring

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is a real simple question for someone simple minded as I am.
How do you get the first character of a string?
.substring(0) ???
or
.substring(1)???
I want to extract the first two
Thanks
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Bart
You want to use the substring method of the String class.
From the API:


Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.


so in your case to get the first two letters of a string your code would look like this:

Then the String firstTwo would contain the first two letters of the String yourString.
hope that helped


------------------
Dave
Sun Certified Programmer for the Java� 2 Platform
 
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Alternately, if you want a 'character', then you need the charAt(int index) function.
firstLetter should contain the character 'a'

So to answer the 'unasked' question, Strings are ZERO based, just like C-style strings, which are zero-based arrays of chars.

If, for whatever reason, you want a C-style char array from a java String, there is a method toCharArray()

And as a last comment Bart, you're not simple minded. You just don't know certain things yet. Which is why places like JavaRanch are pretty cool.
[This message has been edited by Mike Curwen (edited September 06, 2001).]
 
reply
    Bookmark Topic Watch Topic
  • New Topic