Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

strings

 
kevin schmidt
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a set of strings. Some have a '\' in it. Some don't. How do I check a string to see if it contains a '\', cause if it doesn't, I want to leave the string as is, otherwise I want to remove the '\', create two substrings and remove the extra space. TIA.
kevin
 
Joel Cochran
Ranch Hand
Posts: 301
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use the "indexOf()" method to find the position of a character in the String.
int slashPos = s.indexOf( '\' );
If it is not found, the position will equal -1. Then use the "substring()" method to break it out.
if ( slashPos != -1 )
{
firstPart = s.substring( 0 , slashPos );
secondPart = s.substring( slashPos + 1 );
}
HTH
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you writing these slashes yourself?
In a string, the "\" character is used to start an escape sequence. In a string literal the slash must be followed by either b,t,n,f,r,", or ', or another \ if you want to interpret that as an actual slash character. Any other character after the \ is a compiler error.
Rob
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic