I simply cannot find how to do this.
so, I have a String that will be something like this:
do this
then do that
then more of this
and I need to turn this into an array of strings. where every new line is needs to be a separate entry in the array. I need this done so I can process every line or command separately. I can't enter it directly into an array because this is loaded from a text document, and there is some code that removes comments and unnecessary empty lines, and a few more things with the string before it needs to become an array.
thanks in advance!
String s = "do this\nthen do that\nthen more of this";
String[] split = s.split("\n");
Try this:
string.split("(?m)\n");
Related
I am at the beginning chapters in my Java I class. This seems beyond what I have learned thus far.
I have to ask a user to input the first string. It could be anything. Then they have to input a second string. I have to take the first half of the first string and place it in front of the second string, then the other half of the first string and place it at the end of the first string. For example:
Enter something: ----
Enter something: word
Output: --word--
The only thing I've learned up until now is concatenation, indexes, and getting length. I have not learned arrays, if they can be relevant to this. What methods would I use to split this string up when I only know the strings after the user enters them? Even just informing me of unknown method calls would lead me in the right direction. I don't want (and can't) copy anyone's code.
Based on your example this is how you achieve that:
String firstString = "----"; //this should be read in from the user input.
String secondString = "word"; //this too should be read in from the user.
String finalString = firstString.substring(0,firstString.length()/2)+secondString+firstString.substring(firstString.length()/2,firstString.length());
Test code here
You should look into the Java StringAPI for substring. This will help you understand the code above.
You can use the substring method of the String class
something like this should work:
int idxMiddle = (string1.length()-1)/2;
string1.substring(0,idxMiddle) + string2 + string1.substr(idxMiddle);
I'm trying to copy a String array into another String array. However the copy has to contain only parts of each string of the original Array.
For example, If we have
String[] originalArray = {"/data/test2/", "/data/test4/", "/data/dropbox/test5/"}
I want the copy array to be
String[] copyArray = {"test2", "test4", "test5"}
My solution would be to simply iterate through the original array and use regular expression to grab the last part of the string in the originalArray and make a copyArray consisting of those values.
Is the above method valid, or is there a more efficient solution to this? Also what regular expression would I use for this case? The way I'm doing seems a bit too brute forced.
Ideally, I would just manually create the copyArray, but in this case, the size of the originalArray and the precise content is unknown.
Edit:
This seems trivial but for some reason it's not working.
I added the regular expression. It seems to work in the tester but it's not working as I wanted it to in the program. I first converted the originalArray into a String with | appended for the regex.
String pattern = "/\\w+(?=\\||$)/g";
String testArray = originalArray.replaceAll(pattern," ");
However test array is just giving me the original concatenated String without the regex applied.
Up to java 7, you need to code a loop, but java 8 introduced streams that allow a fluent one-line solution:
String[] names = Arrays.stream(originalArray)
.map(s -> s.replaceAll(".*/", ""))
.toArray();
The important bit is the lambda expression to convert the path to the name by using regex to replace everything up to and including the last slash with a blank (effectively removing it).
Your method is fine. Note that the length of an array is always known through its length field. You should create the copy using new String[originalArray.length].
If it is an array of string you could join it using something like | and then apply a single RexEx to the whole string like:
/\w+(?=\||$)/g
Online Demo
There is no need to use regex for this simple requirement. Simply use String#lastIndexOf() to get the index of last / and use String#substring() method to get the desired sub-string.
Sample code:
String[] originalArray = {"/data/test2", "/data/test4", "/data/dropbox/test5"};
String[] copyArray=new String[originalArray.length];
for(int i=0;i<originalArray.length;i++){
copyArray[i]=originalArray[i].substring(originalArray[i].lastIndexOf("/")+1);
}
String[] files(String[] originalArray) {
List<String> copy = new ArrayList<>(originalArray.length);
for (String s : originalArray)
copy.add(originalArray[idx].replaceFirst(".*([^/]*)$", "$1"));
return copy.toArray(new String[copy.size()]);
}
I have some problems with my code while reading the file, this is the entries of my file:
Want
Serious
Try
I Want
I Try
and here is my code
//open the file
openFile();
while(x.hasNext()){
//pass the word into variable
String a = x.next();
//store in array list
Streams.add(a);
}
Since my entries are contains of single-word, and two-words(bigram), the script cannot read it, my script will make a word like "I want" stored in two different array, while i actually want to store the single-word and the bigram into an index.
So, the first index will contain : want, 2nd Serious, 3rd Try, 4th I want, 5th I try
Sorry for the confusing question, any help will be appreciated, thanks :)
Are the entries in your file present in seperate lines. If so, you could use nextLine() instead of next().
!
I have a text, the content looks like [1,'I am java, and I am happy, I am.....'], I want to remove the first integer and the comma. When I was run the code above, but the result start with last comma: I am......
If you only want to remove commas from a String, you can use String.replaceAll(",",""); If you want to replace them by spaces, use String.replaceAll(","," "):
while ((line = br.readLine()) != null) {
contents.append(line.replaceAll(","," ");
}
Also in your code you seem to split the input, but don't use the result of this operation.
You need to use the indexOfReturns the index within this string of the first occurrence of the specified character, starting the search at the specified index..
lastIndexOf Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
System.out.print(s.substring(s.indexOf(",")+1));
Use this following code as:
System.out.println(line.substring(2));
sub string takes the beginning index as a parameter and splits the string from that index to till the end.
Note that you are using lastIndexOf(). Use indexOf() to get the first index as shown below.
System.out.println(test.substring(line.indexOf(',')+1));
I'm taking your String literially, but you could use String#replaceFirst, for example...
String text = "[1,'I am java, and I am happy, I am.....']";
text = text.replaceFirst("\\[\\d,", "[");
System.out.println(text);
Which outputs...
['I am java, and I am happy, I am.....']
If you want to update the file, you are either going to have to read all the lines into some kind of List (modifying them as you please) and once finished, write the List back to the file (after you've closed it after reading it).
Alternatively, you could write each updated line to a second file, once you're finished, close both files, delete the first and rename the second back in it's place...
Try This code:
String[] s=line.splite(",");
String m="";
for(int i=1;i<s.length;i++)
{
String m=m+s[i];
}
br.append(m);
String input = "[1,'I am java, and I am happy, I am.....']";
//Getting String after first comma
String output = StringUtils.substringAfter(input, ",");
System.out.println("Output:"+output);
//replacing commas;
System.out.println("Final o/p:"+StringUtils.replace(output, ",",""));
You can use methods in StringUtils Class for string manipulations. For using StringUtils methods, you need to import apache-commons-lang.jar file. Using this API you can manipulate many String related methods. For more details, you can see the link
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html
I'm working on my second bigger programming project at the moment and I got stuck. I'm using Processing for this project.
What I'm trying to do is retrieve information (used to assign a certain color palette to the individual 'lines' of a horizontal bar chart) from an external text file that contains the following line, using an instance of the java.util.Properties class:
formating = p;p;n;n
My code snippet for importing it looks like this (using a class named 'Import' that handles the BufferedInputStream, etc.):
Import imp = new Import();
Properties properties = imp.importSettings();
The next step reads the 'formating' line from the text file and puts it into a four element String array, using the Semicolon as a delimiter.
String[] formating = properties.getProperty("formating").split(";");
I was expecting for this String array to be identical to the one I would get by creating it in my source code using:
String[] formating2 = {"p", "p", "n", "n"};
But it isn't. It tried a number of things already, including checking for unwanted characters (blanks for example) in each element of my String array, converting my text file or the characters I use for comparison to Unicode, converting the elements of the String array to Chars.
What I can't seem to get working is the following comparison:
for(int i=0;i < formating.length;i++){
println(formating[i]==formating2[i]);
}
which returns 'false' for each iteration of the for-loop.
I'm sure it's just some rookie mistake but it would be nice if someone could point me in the right direction. Thanks in advance!
Nick
comparing strings using == is not safe since Strings are possibly different objects and comparing them, no matter if they contain the same "text" does not compare the texts but the objects. So, you should try it like this:
println(formating[i].equals(formating2[i]));
or if you want to avoid excess spaces and tabs all-together you can also do:
println(formating[i].trim().equals(formating2[i].trim()));