Split by last space including tab space in java - java

I have a string as follows
Esophageal have not 45.3
The end is nigh 23
Maybe (just) (maybe>32) 45.2
Every line ends in a number (both with and without decimal points)
I want to split the line before the last number
I have tried this regex:
myarray[]=null;
myarray=match.split("/\\s+(?=\\S*+$)/");
but it doesn't split it

You can use this
String Str = "Maybe (just) (maybe>32) 45.2";
for (String retval: Str.split("\\s(?=\\b(\\d+(?:\\.\\d+)?)$)")){
System.out.println(retval);
}
Ideone Demo

Just split the string and get the last value of array:
String[] array = "Maybe (just) (maybe>32) 45.2".split(" ");
String firstPart = array[0];
String lastPart = array[array.length-1];
for (int i = 1; i < array.length - 1; i++) {
firstPart += " " + array[i];
}
System.out.println(firstPart);
System.out.println(lastPart);

match.split("[ \\t](?=[.\\d]+([\\n\\r]+|$))");
Results should look like:
Esophageal have not
45.3 The end is nigh
23 Maybe (just) (maybe>32)
45.2

Related

whats the simplest way to write a palindrome string using a while loop in java

I've searched about everywhere but I just can't find anything very concrete. I've been working on this code for awhile now but it keeps stumping me.
public static void main(String[] args) {
System.out.println(palindrome("word"));
}
public static boolean palindrome(String myPString) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();
String reverse = "";
int startIndex = 0;
int str = word.length() -1;
while(str >= 0) {
reverse = reverse + word.charAt(i);
}
}
There's a lot of ways to accomplish this using a while loop.
Thinking about simplicity, you can imagine how could you do this if you had a set of plastic separated character in a table in front of you.
Probably you'll think about get the second character and move it to the begin, then get the third and move to begin, and so on until reach the last one, right?
0123 1023 2103 3210
WORD -> OWRD -> ROWD -> DROW
So, you'll just need two code:
init a variable i with 1 (the first moved character)
while the value of i is smaller than total string size do
replace the string with
char at i plus
substring from 0 to i plus
substring from i+1 to end
increment i
print the string
The process should be:
o + w + rd
r + ow + d
d + row +
drow
Hope it helps
Here is an piece of code I write a while back that uses almost the same process. Hope it helps!
String original;
String reverse = "";
System.out.print("Enter a string: ");
original = input.nextLine();
for(int x = original.length(); x > 0; x--)
{
reverse += original.charAt(x - 1);
}
System.out.println("The reversed string is " +reverse);

index out of range when trying to use substring

I made a simple program to spell-check words. The program has 2 inputs, an array of String that works as a dictionary and a String that is a sentence. The program checks the sentence (word to word) and checks the dictionary to find a simmilar word, then it asks the user if they meant to write the word in the dictionary.
Requirements:
The first 2 characters need to be the same.
The word in the dictionary can only have 2 more characters than the sentence word.
The word in the dictionary can only have 2 different characters than the word in the sentence. (The only characters that count are the ones with index between 0 and the length of the sentence word. E.g. efg and egg|s)
public static String SpellCheck(String[] dictionary, String sentence){
Scanner sc = new Scanner(System.in);
String newSentence = "";
StringTokenizer divisor = new StringTokenizer(sentence);
while(divisor.hasMoreElements()){
String word = divisor.nextToken();
String a = "";
for(int i = 0; i<dictionary.length; ++i){
int n = 0;
if(word.length()>2 && dictionary[i].length()-word.length()<=2 && word.substring(0,2).indexOf(dictionary[i].substring(0,2))==0){
String s1 = word.substring(2,word.length());
String s2 = dictionary[i].substring(2,dictionary[i].length());
for(int k = 0; k<s1.length(); ++k){
String l1 = s1.substring(k,k+1);
String l2 = s2.substring(k,k+1);
if(l1.indexOf(l2)!=0)++n;
}
if(n<=2){
System.out.print(dictionary[i] + "?");
a = sc.nextLine();
if("yes".indexOf(a)==0){
newSentence += dictionary[i] + " ";
break;
}
}
}
}
if("yes".indexOf(a)!=0)newSentence += word + " ";
}
return newSentence;
}
The problem is at the line
String s2 = dictionary[i].substring(2,dictionary[i].length());
It works for the first word in the sentence but in the second time I get an error saying "String index is out of range" and I can't figure out why since I'm using .length() to find the index of the last letter. I hope someone can help me figuring out what's wrong with this program. Thank you!
I believe your error is in the for loop just below where you've said the error is
String s2 = dictionary[i].substring(2,dictionary[i].length());
for(int k = 0; k<s1.length(); ++k){ //HERE
String l1 = s1.substring(k,k+1);
String l2 = s2.substring(k,k+1);
}
When setting l1 and l2, you will be exceeding the bounds of your string index. the for loop should read
for(int k = 0; k < s1.length()-1; ++k){
What if the length is less than 2? Your starting index is 2.

Split sentence by words count in Java

How can I split a sentence into two groups with equal number of words?
Sentence(odd words count) :
This is a sample sentence
Output: part[0] = "This is a "
part[1] = "sample sentence"
Sentence(even words count) :
This is a sample sentence two
Output: part[0] = "This is a "
part[1] = "sample sentence two"
I tried to split the whole sentence into words, getting the index of ((total number of spaces / 2) + 1)th empty space and apply substring. But it is quite messy and I was unable to get the desired result.
Pretty simple solution using Java8
String[] splitted = test.split(" ");
int size = splitted.length;
int middle = (size / 2) + (size % 2);
String output1 = Stream.of(splitted).limit(middle).collect(Collectors.joining(" "));
String output2 = Stream.of(splitted).skip(middle).collect(Collectors.joining(" "));
System.out.println(output1);
System.out.println(output2);
Output on the 2 test strings is:
This is a
sample sentence
This is a
sample sentence two
String sentence ="This is a simple sentence";
String[] words = sentence.split(" ");
double arrayCount=2;
double firstSentenceLength = Math.ceil(words.length/arrayCount);
String[] sentences = new String[arrayCount];
String first="";
String second="";
for(int i=0; i < words.length; i++){
if(i<firstSentenceLength){
first+=words[i]+ " ";
}else{
second+=words[i]+ " ";
}
}
sentences[0]=first;
sentences[1]=second;
I hope this help you.
String sentence = "This is a sample sentence";
String[] words = sentence.split(" +"); // Split words by spaces
int count = (int) ((words.length / 2.0) + 0.5); // Number of words in part[0]
String[] part = new String[2];
Arrays.fill(part, ""); // Initialize to empty strings
for (int i = 0; i < words.length; i++) {
if (i < count) { // First half of the words go into part[0]
part[0] += words[i] + " ";
} else { // Next half go into part[1]
part[1] += words[i] + " ";
}
}
part[1] = part[1].trim(); // Since there will be extra space at end of part[1]

Splitting string data in java with white spaces

I have a string xyz a z. How to split it into xyz az. That is splitting the string into two parts taking first white space as the split point. Thanks
Use String.split with the second limit parameter. Use a limit of 2.
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
Try this
String givenString = "xyz a z";
String[] split = givenString.split(" ");
StringBuffer secondPart = new StringBuffer();
for (int i = 1; i < split.length; i++) {
secondPart.append(split[i]);
}
StringBuffer finalPart = new StringBuffer();
finalPart.append(split[0]);
finalPart.append(" ");
finalPart.append(secondPart.toString());
System.out.println(finalPart.toString());
Do like this
public static void main(String []args){
String a= "xyz a z";
String[] str_array=a.split(" ");
System.out.print(str_array[0]+" ");
System.out.println(str_array[1]+str_array[2]);
}
Try this
String Str = new String("xyz a z");
for (String retval: Str.split(" ", 2)){
System.out.println(retval);
You need to use String.split with limit of 2 as it will be applied (n-1) times, in your case (2-1 = 1 ) time
So it will consider first space only.
But still you will get the result as xyz and a z, you will still have to get rid of that one more space between a z
Try this
String path="XYZ a z";
String arr[] = path.split(" ",2);
String Str = new String("xyz a z");
for(int i=0;i<arr.length;i++)
arr[i] = arr[i].replace(" ","").trim();
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
builder.append(" ");
}
System.out.println(builder.toString());
In the for loop you can append a space between two arrays using builder.append(" ").

Regexp for adding a blank after each character of an String

I'm looking for the way of replacing each char of a Java String for the character+ a blank (except the last one or removing the trailing blank at the end)
The idea is from STACKOVERFLOW return S T A C K O V E R F L O W. Is possible to do this with a regexp or should I iterate the string?
Thanks
"StackOverFlow".replaceAll(".(?!$)", "$0 "));
Go with
str.replaceAll("(?<!^)(?!$)", " ");
or equivalent
str.replaceAll("(?<=.)(?!$)", " ");
...or if you want to add space character just behind non-space character, then use
str.replaceAll("(?<=\S)(?!$)", " ");
...and if you want to prevent double spaces (in case some space is already there), then use
str.replaceAll("(?<=\S)(?!\s)(?!$)", " ");
There's no need for a regex.
Just iterate over the String and use a StringBuilder:
String withSpaces = addSpaces("StackOverflow");
public String addSpaces(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
sb.append(s.charAt(i)).append(" ");
}
return sb.substring(0, sb.length() - 1);
}

Categories

Resources