How should I map a function onto a string array in java? - java

I want to split a string and trim each word in the newly established array. Is there a simple (functional) way in Java how to do it as a one liner without the use of a cycle?
String[] stringarray = inputstring.split(";");
for (int i = 0; i < stringarray.length; i++) {
stringarray[i] = stringarray[i].trim();
}
EDIT: corrected the cycle (Andreas' comment)

You can do it in the following way:
String[] stringarray = inputstring.trim().split("\\s*;\\s*");
Explanation of the regex:
\s* is zero or more times whitespace
\s*;\s* specifies zero or more times whitespace followed by ; which may be followed by zero or more times whitespace

With streams you could do this:
String[] stringarray = Arrays.stream(inputstring.split(";"))
.map(String::trim)
.toArray(String[]::new);

This may not be pure Array solution but a java 8 solution:
String str = " string1 ;string2 ;string3 ;string4;";
String [] s = Arrays.stream(str.split(";")).map(String::trim).collect(Collectors.toList()).toArray(new String[]{});
System.out.println(Arrays.toString(s));

First convert the array to a stream (using the Arrays class), then use the map function, then convert back to array.
https://mkyong.com/java8/java-8-how-to-convert-a-stream-to-array/

Related

How to return only first n number of words in a sentence Java

Say i have a simple sentence as below.
For example, this is what have:
A simple sentence consists of only one clause. A compound sentence
consists of two or more independent clauses. A complex sentence has at
least one independent clause plus at least one dependent clause. A set
of words with no independent clause may be an incomplete sentence,
also called a sentence fragment.
I want only first 10 words in the sentence above.
I'm trying to produce the following string:
A simple sentence consists of only one clause. A compound
I tried this:
bigString.split(" " ,10).toString()
But it returns the same bigString wrapped with [] array.
Thanks in advance.
Assume bigString : String equals your text. First thing you want to do is split the string in single words.
String[] words = bigString.split(" ");
How many words do you like to extract?
int n = 10;
Put words together
String newString = "";
for (int i = 0; i < n; i++) { newString = newString + " " + words[i];}
System.out.println(newString);
Hope this is what you needed.
If you want to know more about regular expressions (i.e. to tell java where to split), see here: How to split a string in Java
If you use the split-Method with a limiter (yours is 10) it won't just give you the first 10 parts and stop but give you the first 9 parts and the 10th place of the array contains the rest of the input String. ToString concatenates all Strings from the array resulting in the whole input String. What you can do to achieve what you initially wanted is:
String[] myArray = bigString.split(" " ,11);
myArray[10] = ""; //setting the rest to an empty String
myArray.toString(); //This should give you now what you wanted but surrouned with array so just cut that off iterating the array instead of toString or something.
This will help you
String[] strings = Arrays.stream(bigstring.split(" "))
.limit(10)
.toArray(String[]::new);
Here is exactly what you want:
String[] result = new String[10];
// regex \s matches a whitespace character: [ \t\n\x0B\f\r]
String[] raw = bigString.split("\\s", 11);
// the last entry of raw array is the whole sentence, need to be trimmed.
System.arraycopy(raw, 0, result , 0, 10);
System.out.println(Arrays.toString(result));

Java: Replace a specific character with a substring in a string at index

I am struggling with how to actually do this. Say I have this string
"This Str1ng i5 fun"
I want to replace the '1' with "One" and the 5 with "Five"
"This StrOneng iFive fun"
I have tried to loop thorough the string and manually replace them, but the count is off. I have also tried to use lists, arrays, stringbuilder, etc. but I cannot get it to work:
char[] stringAsCharArray = inputString.toCharArray();
ArrayList<Character> charArraylist = new ArrayList<Character>();
for(char character: stringAsCharArray) {
charArraylist.add(character);
}
int counter = startPosition;
while(counter < endPosition) {
char temp = charArraylist.get(counter);
String tempString = Character.toString(temp);
if(Character.isDigit(temp)){
char[] tempChars = digits.getDigitString(Integer.parseInt(tempString)).toCharArray(); //convert to number
charArraylist.remove(counter);
int addCounter = counter;
for(char character: tempChars) {
charArraylist.add(addCounter, character);
addCounter++;
}
counter += tempChars.length;
endPosition += tempChars.length;
}
counter++;
}
I feel like there has to be a simple way to replace a single character at a string with a substring, without having to do all this iterating. Am I wrong here?
String[][] arr = {{"1", "one"},
{"5", "five"}};
String str = "String5";
for(String[] a: arr) {
str = str.replace(a[0], a[1]);
}
System.out.println(str);
This would help you to replace multiple words with different text.
Alternatively you could use chained replace for doing this, eg :
str.replace(1, "One").replace(5, "five");
Check this much better approach : Java Replacing multiple different substring in a string at once (or in the most efficient way)
You can do
string = string.replace("1", "one");
Don't use replaceAll, because that replaces based on regular expression matches (so that you have to be careful about special characters in the pattern, not a problem here).
Despite the name, replace also replaces all occurrences.
Since Strings are immutable, be sure to assign the result value somewhere.
Try the below:
string = string.replace("1", "one");
string = string.replace("5", "five");
.replace replaces all occurences of the given string with the specified string, and is quite useful.

How to split a string by comma followed by a colon in java?

I'm a java newbie and I'm curious to know how to split a string that starts with a comma and gets followed by a colon towards the end.
An example of such string would be?
-10,3,15,4:38
5,15,8,2:8
Could it be like this?
sections = line.split(",");
tokens = sections[3].split(":");
or is it even possible to split line which the file is read into twice?
tokens = line.split(",");
tokens = line.split(":");
I also tried this but it gave me an ArrayOutOfBound error
tokens = line.split("[,:]");
Any contribution would be appreciated.
use a regular expression in the split section such as
line.split(",|;");
Haven't tested it but I think you get the idea.
You can also do it this way, if you want it for a general case, the method basically takes in the string array, splits each string at each index in the array and adds them to an ArrayList. You can try it, it works.
public static void splitStrings(String[] str){
String[] temp1 =null;//initialize temp array
List<String> itemList = new ArrayList<String>();
for(int i=0;i<str.length;i++){
temp1=str[i].split(",|:");
for (String item : temp1) {
itemList.add(item);
}
//Only print the final result of collection once iteration has ended
if(i==str.length-1){
System.out.println(itemList);
}
}
I am not sure if I totally understand your question correctly. But if you first want to split by , and then by :, you can call split() function twice
String[] str = {"-10,3,15,4:38", "5,15,8,2:8"};
for (String s: str) {
String[] temp = s.split(",")[3].split(":");
System.out.println(temp[0] + " " + temp[1]);
}
Output:
4 38
2 8

About splits in Java

I'm a Java beginner, so please bear with me if this is an extremely easy answer.
Say I have code that looks like this:
String str;
String [] splits;
str = "The words never line up in such a way ";
splits = str.split(" ");
for (int i = 0; i < splits.length; i++)
System.out.println(splits[i]);
What does Java do at the end of the string? After "way" there is a space; since there is no value after the space does Java decide not to split again?
Thanks so much!
According to the Java documentation for split(), http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String),
The split(String r) is equivalent to the split(String r, 0) method, which will ignore and not include any blank trailing empty strings. Specifically from the docs:
"Trailing empty strings are therefore not included in the resulting
array."
So the last element in the array after the split will be "way"
You can confirm this by executing the code you mentioned.
You will not get any trailing space after delimiter if you use split method. Example
class Main
{
public static void main (String[] args)
{
String str;
String [] splits;
str = "The words never line up in such a way "; // some empty string after delimiter at end
splits = str.split(" ");
for (int i = 0; i < splits.length; i++)
System.out.println(splits[i]);
System.out.println("END");
}
}
OUTPUT
The
words
never
line
up
in
such
a
way
END
see no splitted string for end delimiters.
Now
class Main
{
public static void main (String[] args)
{
String str;
String [] splits;
str = "The words never line up in such a way yeah";
splits = str.split(" ");
for (int i = 0; i < splits.length; i++)
System.out.println(splits[i]);
System.out.println("END");
}
}
OUTPUT
The
words
never
line
up
in
such
a
way
yeah
END
see an extra string after delimiter which is also a empty string but not the trailing, so it will be in the array.
I´ve been looking at javadoc and here what it says about String.split:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
It seems that this method calls .split with two arguments:
The limit parameter controls the number of times the pattern is
applied and therefore affects the length of the resulting array. If
the limit n is greater than zero then the pattern will be applied at
most n - 1 times, the array's length will be no greater than n, and
the array's last entry will contain all input beyond the last matched
delimiter. If n is non-positive then the pattern will be applied as
many times as possible and the array can have any length. If n is zero
then the pattern will be applied as many times as possible, the array
can have any length, and trailing empty strings will be discarded.
thanks

Replacing Only Certain White Spaces In a String

I have string queryInputNameString that is equal to fir, spotted owl and I'm trying to use replaceAll() to remove the white spaces and split() to separate the elements in the inputNameArray array when a comma occurs.
String noSpaces = queryInputNameString.replaceAll("\\s+","");
String[] inputNameArray = noSpaces.split("\\,");
So far the above returns:
fir
spottedowl
but I would like it to only remove the white spaces that occurs immediately before or after a comma and return this:
fir
spotted owl
How can I make my code ignore white spaces that are not preceded/followed by a comma?
Thanks.
Since split() accepts a regex as argument, you can directly do this:
String[] inputNameArray = queryInputNameString.split("\\s*\\,\\s*");
Otherwise, if you really want to replace only spaces after a comma, you can use:
String noSpaces = queryInputNameString.replaceAll(",\\s+",",");
You actually do not have to use more sophisticated regex. If you just split by comma first and then trim each array element you will get the desired result.
This approach might prove to be less effective when dealing with a lot of data.
String[] inputArray = queryInputNameString.split(",");
for (int i=0; i < inputArray.length, ++i) {
inputArray[i] = inputArray[i].trim();
}

Categories