Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split the string on forward slash

Tags:

java

string

split

I have a code which I wanted to split based on the forward slash "/".

Whenever I have a regex split based on "////" it never splits and gives me the whole string back. I tried replacing with file separator which gives "\" and then splitting with "\\" works but not the below code.

Below is the code tested

package org.saurav.simpletests.string;  import java.io.File;  public class StringManipulator {      public static void main(String a[]){         String testString ="/UserId/XCode/deep";          //testString = testString.replace("/", File.separator);         //testString = testString.replace("/", "_");         testSplitStrings(testString);     }      /**      * Test the split string      * @param path      */     public static void testSplitStrings(String path){         System.out.println("splitting of sprint starts \n");         String[] paths = path.split("////");         for (int i = 0; i < paths.length; i++) {             System.out.println("paths::"+i+" "+paths[i]+"\n");         }         System.out.println("splitting of sprint ends");     } } 

cheers, Saurav

like image 935
saurav Avatar asked Jul 14 '14 09:07

saurav


People also ask

How do you use a forward slash in a string in Python?

Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n represents a line feed, and \t represents a tab. When specifying a path, a forward slash (/) can be used in place of a backslash. Two backslashes can be used instead of one to avoid a syntax error.

How do you split a string with a backslash in Python?

You can split a string by backslash using a. split('\\') .


2 Answers

There is no need to escape forward slashes. Your code works fine if you just do:

String[] paths = path.split("/"); 
like image 131
Keppil Avatar answered Sep 22 '22 11:09

Keppil


i wanted to check validation of input date in the format dd/mm/yyyy so need to split my string around / You can do it simply by:

String spl[]=str.split("/"); int date=Integer.parseInt(spl[0]); int month=Integer.parseInt(spl[1]); int year=Integer.parseInt(spl[2]); 
like image 24
shreshth Avatar answered Sep 23 '22 11:09

shreshth