String str = "D:*Course 2007 Sem 2*WXET3309*WXET3309_Lab*WXET3309_Lab 2.doc";
		System.out.println(str);
		String[] word = str.split("\\*");
		
		int i = word.length; //length is 1 more than array
		i--; //last index = last string
		System.out.println(word[i]);

The code above is code to get the last string separated by the symbol *. I wonder how should the code be modify if the string is changed to D:\Course 2007 Sem 2\WXET3309\WXET3309_Lab\WXET3309_Lab 2.doc or String str = "D:\\Course 2007 Sem 2\\WXET3309\\WXET3309_Lab\\WXET3309_Lab 2.doc";. Anyone would like to help me to solve this problem?

if "\" were the separator, you would do

str.split("\\\\")

the reason is that the argument to split() is compiled into a regular expression; and characters which are special in regex need to be quoted

the backslash is also the escape characters for strings in general, and needs to be doubled

a better way is to use the Pattern.quote() method to quote strings, so you don't have to escape special characters, like

str.split(Pattern.quote("*"));
str.split(Pattern.quote("\\"));

for "*" and "\" separators respectively

thx, it is really a helpful explanation for me to better understand wat is going on actually.

the alternatives way u suggested to me seem not working. My compiler showed me an error message with description "cannot find symbol variable Pattern".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.