Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string question

Status
Not open for further replies.

cajchris

Programmer
Oct 13, 2005
57
GB
if for example i have the following file name:

232323231_test_file.txt

but only want to get test_file.txt back how can i make sure that when i get to the first instance of the '_' character i take whatever is after it and return it.

regards,
cajchris
 
Inside the String class:

- indexOf will give you the first ocurrence inside the string.

- substring will return the piece of that string after a given position.

Cheers,
Dian
 
More on String commands at:


More on Java commands at:


You might also find the length property of Strings helpful. stringVariable.length returns the int length of stringVariable (NOTE: this value is one greater than the index of the last character in the String, making it a frequently good choice for use with the second parameter of the substring method).

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
Only if the number part is fixed length, then you can use position to get a substring.

You can use a loop to get the first '_' position.
Code:
Char ch = '_'

for(int i=0;i<filename.length();i++){
   if(filename.charAt(i) == ch){
      return filename.subString(i);
   }
}



Chinese Java Faq Forum
 
Seeing as everyone is wading in with examples now ...

Code:
return filename.substring(filename.indexOf("_") +1, filename.length());

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
sedj silently pointed out a flaw in my mention of the length property in that it is not a property, but a method. Arrays have a length property.

Code:
String myArray[] = new String[5];
String myString = "12345";
boolean myBool = (myArray[b].length[/b] == myString[b].length()[/b]); //true

Sorry about any confusion.

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top