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

How to get or replace the backslash in Java string

 
Sky Loi
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I try the followings:
System.out.println("12345\6"); // it get special char output like '12345'

I want to get or check this backslash by substring(..), charAt(..) or regx functions but they does not work. Is there any way to make it? Many thanks.



 
Henry Wong
author
Marshal
Pie
Posts: 21114
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println("12345\6"); // it get special char output like '12345'


This is because the backslash has special meaning in a string literal. If you want an actual backslash, you will need to escape it -- like so...



In your example, there isn't a backslash in the string... as showned by the printout.



I want to get or check this backslash by substring(..), charAt(..) or regx functions but they does not work. Is there any way to make it? Many thanks.


First of all, I am not sure what you are asking. Second, I don't know how it related to the previous statement.

Henry
 
Sky Loi
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Henry, thanks for quick reply.

I am doing some codes to validate a string not to include backslash "\". For example, user input "12345\6" and I have to check if it contains backslash. I try the followings but they does not work:

loop check:
for (int i=0; i<inputString.length(); i++){
char charValue = inputString.charAt(i);
if (charValue=='\\'){
return false;
}
}

or regx check
if (!Pattern.matches("[^\\\\]+", inputString)) return false;



>
 
Henry Wong
author
Marshal
Pie
Posts: 21114
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am doing some codes to validate a string not to include backslash "\". For example, user input "12345\6" and I have to check if it contains backslash. I try the followings but they does not work:


If the user actually inputted the data, as you say, then it should work. If however, you are testing it with a string literal, then it won't work. The string literal will treat the backslash as a escape character, and the number following defines the ASCII of the specified character. So, in that case, there isn't any backslash in the string.

Henry
 
Mikko Kohtamäki
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic