简体   繁体   中英

Manipulate the special character '\' in a JAVA string

I have this String :

pathfileshtml.get(b) = C:\Users\Netrill\workspace\find and fix\JAS_DOC\JAS\PRD_15M\JAS_JAE\JAS_JAE\JAS_JAE_0.1.html

I used this :

String cartella = pathfileshtml.get(b).substring(0,pathfileshtml.get(b).lastIndexOf("/"));

the Exception is String index of range -1 in SO Windows, but it' s ok on MAC. I need now the Windows version . How i can manipulate the character '\\' in a JAVA string on Windows? Thanks

The \\ character is called an escape character.

It is used for adding characters such as \\n and \\b .

If you want to use \\ you must type \\\\ to have it escape itself.

I think that you are taking the wrong approach to this.

Assuming that you are on a Windows machine trying to manipulate a Windows pathname, you should be doing something like this to parse the pathname string as a Path object:

 Path path = FileSystems.getDefault().getPath(pathString);

Once you have the Path you can perform a variety of operations. For instance, to get the last name in the path:

 String filename = path.getFileName();

Using the Path class avoids the need to parse the pathname yourself, and it (largely) insulates you from platform specific pathname syntax issues. (The code above should work on Mac OSX, UNIX, Linux and so on ... as well as Windows.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM