This question already has answers here:
How to combine paths in Java?
(12 answers)
Closed 9 years ago.
I want to combine the strings "test/" and "/go" as "test/go".
How can I do that?
Using only java.io.File the easiest way is to do:
String combined_path = new File("test/", "/go").getPath();
FilenameUtils.normalize() from Apache Commons IO does what you want.
example:
FilenameUtils.normalize("foo/" + "/bar");
returns the string "foo/bar"
As suggested by Jon Skeet here
public static String combine (String path1, String path2)
{
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
Append both the strings and replace // with / as below
"test//go".replace("//", "/")
Output: test/go
String test = "test/";
String go = "/go";
String result = test + go.substring(1);
Here's a Guava method that joins an Iterable<String> of items with a char, after trimming all instances of this character from beginning and end of the items:
public static String joinWithChar(final Iterable<String> items,
final char joinChar){
final CharMatcher joinCharMatcher = CharMatcher.is(joinChar);
return Joiner.on('/').join(
Iterables.transform(items, new Function<String, String>(){
#Override
public String apply(final String input){
return joinCharMatcher.trimFrom(input);
}
}));
}
Usage:
System.out.println(joinWithChar(Arrays.asList("test/", "/go"), '/'));
Output:
test/go
This solution
is not restricted to file paths, but to any types of Strings
will not replace any characters found inside the tokens, only trim them from the boundaries
Supposed this is a question related to file names, than take a look at apache-commons-io and its FilenameUtils class
final String test = "test/";
final String go ="/go";
System.out.println(FilenameUtils.normalize(test + go));
output on windows:
test\go
The normalize method will do much more for you, e.g. change '/' to '\' on windows systems.
By the way congrat's to your reputation score by nearly just asking questions :-)
Even simpler:
"test/" + "." + "/go"
Related
I want to create a csv file in which delimiter is comma seperated.While csv is read it make s5 string in comma seperation. Want to keep s5 string in single column.
String s1="quick";
String s2="brown";
String s3="fox";
String s4="jump";
String s5="over,the,lazy,dog";
String csvRecord = String.format("%s,%s,%s,%s,%s", s1,s2,s3,s4,s5);
Can anybody help me out, as i am new to strings.
I think you need to add them in a double string.
Try this:
String s5="\"over,the,lazy,dog\"";
Just as other answers mentioned, you have to actually consider many special cases and the most typical two special cases will be: comma and double quotes.
As Chewtoy enclosed, the CSV wiki has clearly specify the format as:
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00
To handle these two cases, you can try something as:
public class CsvAddComma {
public static void main(String... args) {
List<String> list = new ArrayList<>();
list.add("quick");
list.add("over,the,lazy,dog");
list.add("Venture \"Extended Edition, Very Large\"");
list.stream()
.map(s -> convertToCsvFormat(s))
.forEach(System.out::println);
}
private static String convertToCsvFormat(String input) {
if (input.contains("\"")) {
input = input.replaceAll("\"", "\"\"");
}
if (input.contains(",")) {
input = String.format("\"%s\"", input);
}
return input;
}
}
And the output:
quick
"over,the,lazy,dog"
"Venture ""Extended Edition, Very Large"""
As for other special cases, you need to handle them according to your current case. Perhaps they can be ignored, perhaps not.
To include a delimiter in the data, you have to enclose the field with double quotes in the resulting csv:
quick,brown,fox,jump,"over,the,lazy,dog"
If there are double quotes inside some fields those have to be escaped:
123,"24"" monitor, Samsung",456 // Windows style
123,"24\" monitor",456 // Linux style
You don't have to quote all the fields, only those containing a delimiter or a double quote (or a newline).
See RFC4180 for more details on the csv common format.
Unless you are toying with some assignment you absolutely NEED a CSV library to handle this for you. You also need to care about line endings and other quotes inside the values, not only the delimiter
Try the following code with univocity-parsers:
CsvWriterSettings settings = new CsvWriterSettings();
CsvWriter writer = new CsvWriter(settings);
String result = writer.writeRowToString(s1,s2,s3,s4,s5);
Hope this helps.
Disclaimer: I'm the author of this library. It's open source and free (Apache 2.0 license)
I have an string str of unknown length (but not null) and a given maximum length len, this has to fit in. All I want to do, is to cut the string at len.
I know that I can use
str.substring(0, Math.min(len, str.length()));
but this does not come handy, if I try to write stacked code like this
code = str.replace(" ", "").left(len)
I know that I can write my own function but I would prefer an existing solution. Is there an existing left()-function in Java?
There's nothing built in, but Apache commons has the StringUtils class which has a suitable left function for you.
If you don't want to add the StringUtils Library you can still use it the way you want like so:
String string = (string.lastIndexOf(",") > -1 )?string.substring(0, string.lastIndexOf(",")): string;
Use Split.
String str = "Result string Delimiter Right String";
System.out.println(str.split("Delimiter")[0].trim());
Output: "Result string"
No there is not left() in the String class, as you can refer API. But as #Mark said Apache StringUtils has several methods: leftPad(), rightPad(), center() and repeat(). You can also check
this:http://www.jdocs.com/lang/2.1/org/apache/commons/lang/StringUtils.html
You can use String Format
In this example the format specifier "%-9s" means minimum 9 characters left justified (-).
"%-9.9s" means maximum 9 characters.
System.out.println (String.format("%-9.9s","1234"));
System.out.println (String.format("%-9.9s","123456789ABCD"));
int len=9;
System.out.println (String.format("%-"+len+"."+len+"s","123456789ABCD"));
Prints:
1234
123456789
123456789
in OP's case it would be something like this:
static final int MAXLEN=9;
code = String.format("%-"+MAXLEN+"."+MAXLEN+"s",str.replace(" ", ""));
put the below function in a class:
public static String getLeftString(String st,int length){
int stringlength=st.length();
if(stringlength<=length){
return st;
}
return st.substring((stringlength-length));
}
in my case I want to get date only.
String s = "date:2021-01-01";
int n = s.length() - 10; //10 was the length of the date
String result = s.substring(n);
the result will be "2021-01-01";
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
so I have a large list of websites and I want to put them all in a String variable. I know I can not individually go to all of the links and escape the //, but is there is over a few hundred links. Is there a way to do a "block escape", so everything in between the "block" is escaped? This is an example of what I want to save in the variable.
String links="http://website http://website http://website http://website http://website http://website"
Also can anyone think of any other problems I might run into while doing this?
I made it htp instead of http because I am not allowed to post "hyperlinks" according to stack overflow as I am not at that level :p
Thanks so much
Edit: I am making a program because I have about 50 pages of a word document that is filled with both emails and other text. I want to filter out just the emails. I wrote the program to do this which was very simple, not I just need to figure away to store the pages in a string variable in which the program will be run on.
Your question is not well-written. Improve it, please. In its current format it will be closed as "too vague".
Do you want to filter e-mails or websites? Your example is about websites, you text about e-mails. As I don't know and I decided to try to help you anyway, I decided to do both.
Here goes the code:
private static final Pattern EMAIL_REGEX =
Pattern.compile("[A-Za-z0-9](:?(:?[_\\.\\-]?[a-zA-Z0-9]+)*)#(:?[A-Za-z0-9]+)(:?(:?[\\.\\-]?[a-zA-Z0-9]+)*)\\.(:?[A-Za-z]{2,})");
private static final Pattern WEBSITE_REGEX =
Pattern.compile("http(:?s?)://[_#\\.\\-/\\?&=a-zA-Z0-9]*");
public static String readFileAsString(String fileName) throws IOException {
File f = new File(fileName);
byte[] b = new byte[(int) f.length()];
InputStream is = null;
try {
is = new FileInputStream(f);
is.read(b);
return new String(b, "UTF-8");
} finally {
if (is != null) is.close();
}
}
public static List<String> filterEmails(String everything) {
List<String> list = new ArrayList<String>(8192);
Matcher m = EMAIL_REGEX.matcher(everything);
while (m.find()) {
list.add(m.group());
}
return list;
}
public static List<String> filterWebsites(String everything) {
List<String> list = new ArrayList<String>(8192);
Matcher m = WEBSITE_REGEX.matcher(everything);
while (m.find()) {
list.add(m.group());
}
return list;
}
To ensure that it works, first lets test the filterEmails and filterWebsites method:
public static void main(String[] args) {
System.out.println(filterEmails("Orange, pizza whatever else joe#somewhere.com a lot of text here. Blahblah blah with Luke Skywalker (luke#starwars.com) hfkjdsh fhdsjf jdhf Paulo <aaa.aaa#bgf-ret.com.br>"));
System.out.println(filterWebsites("Orange, pizza whatever else joe#somewhere.com a lot of text here. Blahblah blah with Luke Skywalker (http://luke.starwars.com/force) hfkjdsh fhdsjf jdhf Paulo <https://darth.vader/blackside?sith=true&midclorians> And the http://www.somewhere.com as x."));
}
It outputs:
[joe#somewhere.com, luke#starwars.com, aaa.aaa#bgf-ret.com.br]
[http://luke.starwars.com/force, https://darth.vader/blackside?sith=true&midclorians, http://www.somewhere.com]
To test the readFileAsString method:
public static void main(String[] args) {
System.out.println(readFileAsString("C:\\The_Path_To_Your_File\\SomeFile.txt"));
}
If that file exists, its content will be printed.
If you don't like the fact that it returns List<String> instead of a String with items divided by spaces, this is simple to solve:
public static String collapse(List<String> list) {
StringBuilder sb = new StringBuilder(50 * list.size());
for (String s : list) {
sb.append(" ").append(s);
}
sb.delete(0, 1);
return sb.toString();
}
Sticking all together:
String fileName = ...;
String webSites = collapse(filterWebsites(readFileAsString(fileName)));
String emails = collapse(filterEmails(readFileAsString(fileName)));
I suggest that you save your Word document as plain text. Then you can use classes from the java.io package (such as Scanner to read the text).
To solve the issue of overwriting the String variable each time you read a line, you can use an array or ArrayList. This is much more ideal than holding all the web addresses in a single String because you can easily access each address individually whenever you like.
For your first problem, take all the text out of word, put it in something that does regular expressions, use regular expressions to quote each line and end each line with +. Now edit the last line and change + to ;. Above the first line write String links =. Copy this new file into your java source.
Here's an example using regexr.
To answer your second question (thinking of problems) there is an upper limit for a Java string literal if I recall correctly 2^16 in length.
Oh and Perl was basically written for you to do this kind of thing (take 50 pages of text and separate out what is a url and what is an email)... not to mention grep.
I'm not sure what kind of 'list of websites' you're referring to, but for eg. a comma-separated file of websites you could read the entire file and use the String split function to get an array, or you could use a BufferedReader to read the file line by line and add to an ArrayList.
From there you can simply loop the array and append to a String, or if you need to:
do a "block escape", so everything in between the "block" is escaped
You can use a Regular Expression to extract parts of each String according to a pattern:
String oldString = "<someTag>I only want this part</someTag>";
String regExp = "(?i)(<someTag.*?>)(.+?)(</someTag>)";
String newString = oldString.replaceAll(regExp, "$2");
The above expression would remove the xml tags due to the "$2" which means you're interested in the second group of the expression, where groups are identified by round brackets ( ).
Using "$1$3" instead should then give you only the surrounding xml tags.
Another much simpler approach to removing certain "blocks" from a String is the String replace function, where to remove the block you could simply pass in an empty string as the new value.
I hope any of this helps, otherwise you could try to provide a full example with you input "list of websites" and the output you want.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to upper case every first letter of word in a string?
Most efficient way to make the first character of a String lower case?
I want to convert the first letter of a string to upper case. I am attempting to use replaceFirst() as described in JavaDocs, but I have no idea what is meant by regular expression.
Here is the code I have tried so far:
public static String cap1stChar(String userIdea)
{
String betterIdea, userIdeaUC;
char char1;
userIdeaUC = userIdea.toUpperCase();
char1 = userIdeaUC.charAt(0);
betterIdea = userIdea.replaceFirst(char1);
return betterIdea;
}//end cap1stChar
The compiler error is that the argument lists differ in lengths. I presume that is because the regex is missing, however I don't know what that is exactly.
Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.
What replaceFirst() does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.
What you want to do is convert the string to an array using the String class' charAt() method, and then use Character.toUpperCase() to change the character to upper case (obviously). Your code would look like this:
char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);
Or, if you feel comfortable with more complex, one-lined java code:
betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);
Both of these do the same thing, which is converting the first character of userIdea to an upper case character.
Or you can do
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
public static String cap1stChar(String userIdea)
{
char[] stringArray = userIdea.toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
return userIdea = new String(stringArray);
}
Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.
Try this.
betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())
String toCamelCase(String string) {
StringBuffer sb = new StringBuffer(string);
sb.replace(0, 1, string.substring(0, 1).toUpperCase());
return sb.toString();
}
userIdeaUC = userIdea.substring(0, 1).toUpperCase() + userIdea.length() > 1 ? userIdea.substring(1) : "";
or
userIdeaUC = userIdea.substring(0, 1).toUpperCase();
if(userIdea.length() > 1)
userIdeaUC += userIdea.substring(1);
For completeness, if you wanted to use replaceFirst, try this:
public static String cap1stChar(String userIdea)
{
String betterIdea = userIdea;
if (userIdea.length() > 0)
{
String first = userIdea.substring(0,1);
betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
}
return betterIdea;
}//end cap1stChar
This question already has answers here:
Named placeholders in string formatting
(23 answers)
Closed 1 year ago.
So, we all should know that you can include variables into strings by doing:
String string = "A string " + aVariable;
Is there a way to do it like:
String string = "A string {aVariable}";
In other words: Without having to close the quotation marks and adding plus signs. It's very unattractive.
You can always use String.format(....). i.e.,
String string = String.format("A String %s %2d", aStringVar, anIntVar);
I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.
This is called string interpolation; it doesn't exist as such in Java.
One approach is to use String.format:
String string = String.format("A string %s", aVariable);
Another approach is to use a templating library such as Velocity or FreeMarker.
Also consider java.text.MessageFormat, which uses a related syntax having numeric argument indexes. For example,
String aVariable = "of ponies";
String string = MessageFormat.format("A string {0}.", aVariable);
results in string containing the following:
A string of ponies.
More commonly, the class is used for its numeric and temporal formatting. An example of JFreeChart label formatting is described here; the class RCInfo formats a game's status pane.
Since Java 15, you can use a non-static string method called String::formatted(Object... args)
Example:
String foo = "foo";
String bar = "bar";
String str = "First %s, then %s".formatted(foo, bar);
Output:
"First foo, then bar"
Apache Commons StringSubstitutor can be used.
import org.apache.commons.text.StringSubstitutor;
// ...
Map<String, String> values = new HashMap<>();
values.put("animal", "quick brown fox");
values.put("target", "lazy dog");
StringSubstitutor sub = new StringSubstitutor(values);
String result = sub.replace("The ${animal} jumped over the ${target}.");
// "The quick brown fox jumped over the lazy dog."
This class supports providing default values for variables.
String result = sub.replace("The number is ${undefined.property:-42}.");
// "The number is 42."
To use recursive variable replacement, call setEnableSubstitutionInVariables(true);.
Map<String, String> values = new HashMap<>();
values.put("b", "c");
values.put("ac", "Test");
StringSubstitutor sub = new StringSubstitutor(values);
sub.setEnableSubstitutionInVariables(true);
String result = sub.replace("${a${b}}");
// "Test"
you can use String format to include variables within strings
i use this code to include 2 variable in string:
String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);