How to populate with previous value in ; separated string? - java

I have a string separated by semicolon like this:
"11;21;12;22;13;;14;24;15;25".
Look one value is missing after 13.
I Want to populate that missing number with 13(previous value) and store it into another string.

Try this.
static final Pattern PAT = Pattern.compile("([^;]+)(;;+)");
public static void main(String[] args) {
String input = "11;21;12;22;13;;;14;24;15;25";
String output = PAT.matcher(input)
.replaceAll(m -> (m.group(1) + ";").repeat(m.group(2).length()));
System.out.println(output);
}
output:
11;21;12;22;13;13;13;14;24;15;25

What have you tried so far?
You could solve this problem in many ways i think. If you like to use regular expression, you could do it that way: ([^;]*);;+.
Or you could use a simple String.split(";"); and iterate over the resulting array. Every empty string indicates that there was this ;;

String str = "11;21;12;22;13;;14;24;15;25";
String[] a = str.split(";");
for(int i=0; i<a.length; i++){
if(a[i].length()==0){
System.out.println(a[i-1]);
}
}

Related

Replace words in parenthesis

I have a question about replacing words. I have some strings, each of which looks like this:
String string = "today is a (happy) day, I would like to (explore) more about Java."
I need to replace the words that have parentheses. I want to replace "(happy)" with "good", and "(explore)" with "learn".
I have some ideas, but I don't know how.
for (int i = 0; i <= string.length(), i++) {
for (int j = 0; j <= string.length(), j++
if ((string.charAt(i)== '(') && (string.charAt(j) == ')')) {
String w1 = line.substring(i+1,j);
string.replace(w1, w2)
}
}
}
My problem is that I can only replace one word with one new word...
I am thinking of using a scanner to prompt me to give a new word and then replace it, how can I do this?
The appendReplacement and appendTail methods of Matcher are designed for this purpose. You can use a regex to scan for your pattern--a pair of parentheses with a word in the middle--then do whatever you need to do to determine the string to replace it with. See the javadoc.
An example, based on the example in the javadoc. I'm assuming you have two methods, replacement(word) that tells what you want to replace the word with (so that replacement("happy") will equal "good" in your example), and hasReplacement(word) that tells whether the word has a replacement or not.
Pattern p = Pattern.compile("\\((.*?)\\)");
Matcher m = p.matcher(source);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String word = m.group(1);
String newWord = hasReplacement(word) ? replacement(word) : m.group(0);
m.appendReplacement(sb, newWord); // appends the replacement, plus any not-yet-used text that comes before the match
}
m.appendTail(sb); // appends any text left over after the last match
String result = sb.toString();
Use below code for replacing the string.
String string = "today is a (happy) day, I would like to (explore) more about Java.";
string = string.replaceAll("\\(happy\\)", "good");
string = string.replaceAll("\\(explore\\)", "learn");
System.out.println(string);`
What you can do is run a loop from 0 to length-1 and if loop encounters a ( then assign its index to a temp1 variable. Now go on further as long as you encounter ).Assign its index to temp2 .Now you can replace that substring using string.replace(string.substring(temp1+1,temp2),"Your desired string")).
No need to use the nested loops. Better use one loop and store the index when you find opening parenthesis and also for close parenthesis and replace it with the word. Continue the same loop and store next index. As you are replacing the words in same string it changes the length of string you need to maintain copy of string and perform loop and replace on different,
Do not use nested for loop. Search for occurrences of ( and ). Get the substring between these two characters and then replace it with the user entered value. Do it till there are not more ( and ) combinations left.
import java.util.Scanner;
public class ReplaceWords {
public static String replaceWords(String s){
while(s.contains(""+"(") && s.contains(""+")")){
Scanner keyboard = new Scanner(System.in);
String toBeReplaced = s.substring(s.indexOf("("), s.indexOf(")")+1);
System.out.println("Enter the word with which you want to replace "+toBeReplaced+" : ");
String replaceWith = keyboard.nextLine();
s = s.replace(toBeReplaced, replaceWith);
}
return s;
}
public static void main(String[] args) {
String myString ="today is a (happy) day, I would like to (explore) more about Java.";
myString = replaceWords(myString);
System.out.println(myString);
}
}
This snippet works for me, just load the HashMap up with replacements and iterate through:
import java.util.*;
public class Test
{
public static void main(String[] args) {
String string = "today is a (happy) day, I would like to (explore) more about Java.";
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("\\(happy\\)", "good");
hm.put("\\(explore\\)", "learn");
for (Map.Entry<String, String> entry : hm.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
string = string.replaceAll(key, value);
}
System.out.println(string);
}
}
Remember, replaceAll takes a regex, so you want it to display "\(word\)", which means the slashes themselves must be escaped.

Java - Split and trim in one shot

I have a String like this : String attributes = " foo boo, faa baa, fii bii," I want to get a result like this :
String[] result = {"foo boo", "faa baa", "fii bii"};
So my issue is how should to make split and trim in one shot i already split:
String[] result = attributes.split(",");
But the spaces still in the result :
String[] result = {" foo boo", " faa baa", " fii bii"};
^ ^ ^
I know that we can make a loop and make trim for every one but I want to makes it in shot.
Use regular expression \s*,\s* for splitting.
String result[] = attributes.split("\\s*,\\s*");
For Initial and Trailing Whitespaces
The previous solution still leaves initial and trailing white-spaces. So if we're expecting any of them, then we can use the following solution to remove the same:
String result[] = attributes.trim().split("\\s*,\\s*");
Using java 8 you can do it like this in one line
String[] result = Arrays.stream(attributes.split(",")).map(String::trim).toArray(String[]::new);
If there is no text between the commas, the following expression will not create empty elements:
String result[] = attributes.trim().split("\\s*,+\\s*,*\\s*");
You can do it with Google Guava library this way :
List<String> results = Splitter.on(",").trimResults().splitToList(attributes);
which I find quite elegant as the code is very explicit in what it does when you read it.
ApaceCommons StringUtils.stripAll function can be used to trim individual elements of an array. It leaves the null as null if some of your array elements are null.
Here,
String[] array = StringUtils.stripAll(attributes.split(","));
create your own custom function
private static String[] split_and_trim_in_one_shot(String string){
String[] result = string.split(",");
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
Overload with a consideration for custom delimiter
private static String[] split_and_trim_in_one_shot(String string, String delimiter){
String[] result = string.split(delimiter);
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
with streams
public static List<String> split(String str){
return Stream.of(str.split(","))
.map(String::trim)
.map (elem -> new String(elem))//optional
.collect(Collectors.toList());
What about spliting with comma and space:
String result[] = attributes.split(",\\s");
// given input
String attributes = " foo boo, faa baa, fii bii,";
// desired output
String[] result = {"foo boo", "faa baa", "fii bii"};
This should work:
String[] s = attributes.trim().split("[,]");
As answered by #Raman Sahasi:
before you split your string, you can trim the trailing and leading spaces. I've used the delimiter , as it was your only delimiter in your string
String result[] = attributes.trim().split("\\s*,[,\\s]*");
previously posted here: https://blog.oio.de/2012/08/23/split-comma-separated-strings-in-java/
Best way is:
value.split(",").map(function(x) {return x.trim()});

Regex for int Array

I need to validate a string argument if it can be converted to an int Array.
String pattern = "(\\d+[,])+";
String test = "18,32,5,8,10";
test2.matches(pattern2) //returns false as i requires , in the end
Is there any way to ignore last ' , '
Use a group construct to specify that digits should be followed by (, digits) ...
\\d+(?:,\\d+)+
Regex for both array and single element
(\d|\[(\d|,\s*)*])
This regex will work for you (checks for a "valid array") :
public static void main(String[] args) {
String s = "18,32,5,8,10";
System.out.println(s.matches("(?!.*,$)(?!,.*$)(\\d+(?:,|$))+"));
}
Checks and fails for:
multiple continuous commas
comma at beginning
comma at end
You can try
Pattern = "^\d+(,\d+)*$"
text = "10,5,10" (TRUE)
text = "10,5,10," (FALSE)
text = "10,5,10 " (FALSE)
Since I don't know how to use regex and if I were in your place then this would have been my way to do so
String test = "18,32,5,8,10";
String str[]=test.split(",");
int ar[] = new int[str.length];
for(int i = 0; i<ar.length; i++){
ar[i] = Integer.parseInt(str[i]);
}
The problem in this code if any I can see is this that call to parseInt() method must be wrapped in try-catch as it can throw NumberFormatException if your string contains value other than digit and comma(,).

How to extract specific letters in string with java

I have some expression in a Java string and a would get the letter, which was on the left side and on the right side of a specific sign.
Here are two examples:
X-Y
X-V-Y
Now, I need to extract in the first example the letter X and Y in a separate string. And in the second example, I need to extract the letters X, V and Y in a separate string.
How can i implemented this requirement in Java?
Try with:
String input = "X-V-Y";
String[] output = input.split("-"); // array with: "X", "V", "Y"
use String.split method with "-" token
String input = "X-Y-V"
String[] output = input.split("-");
now in the output array there will be 3 elements X,Y,V
String[] results = string.split("-");
do like this
String input ="X-V-Y";
String[] arr=input.split("-");
output
arr[0]-->X
arr[1]-->V
arr[2]-->Y
I'm getting in on this too!
String[] terms = str.split("\\W"); // split on non-word chars
You can use this method :
public String[] splitWordWithHyphen(String input) {
return input.split("-");
}
you can extract and handle a string by using the following code:
String input = "x-v-y";
String[] extractedInput = intput.split("-");
for (int i = 0; i < extractedInput.length - 1; i++) {
System.out.print(exctractedInput[i]);
}
Output: xvy

Remove regex from string array

I need to remove a ';' from a string array. Any solutions?
What I did in my class was retrieving a long piece of string which are connected without spaces
(thisisalongpieceofstringtobeseparated)
I separated them by inserting a ';' between them
(this;is;a;long;piece;of;string;to;be;separated;)
Then I used .split(";") to add them to an array. All is successful but the last index which has a ';'.
this
is
a
long
piece
of
string
to
be
separated;
Need to remove the last ;
As requested, code is below.
while (line != null) {
if(line.contains("../../"))
{
int startIndex = line.indexOf("../../") + 6;
int endIndex = line.indexOf(">", startIndex + 1);
String abc = "http://www.google.com/";
String imageSrc = line.substring(startIndex,endIndex);
//complete full url
String xyz = abc +imageSrc;
xyz = xyz.substring(0,xyz.indexOf('"'));
xyz = xyz +";";
content += xyz;
mStrings = content.split(";");
String str="This; is; my; test;";
String[] strArr=str.split(";");
for(int i=0;i<strArr.length;i++)
{
System.out.println("Str:::"+strArr[i]);
// add strArr[i] to an array or go through Arrays.toString()
}
Nothing special in the code, i mean if you are using spilt() then it's already worked for you, if not then there is something wrong with your code,Post your code to see what exactly wrong with your code or else do this way
I don't think you're telling us the whole story, because a trailing ; will be ignored when you split on ;. See for yourself by running this test code:
public static void main(String[] args) {
System.out.println(Arrays.toString("a;b;c;".split(";")));
}
Output:
[a, b, c]
The "answer" is to do nothing! It should already work!
Wouldn't it be easiest just to remove the final ; from the string before splitting it ? That is, remove the last character (presuming that is always going to be ;) :
var newStr = str.substring(0, str.length-1);
And then split on that string instead.
Mikel's solution is a lot less work, but you could also use a StringTokenizer and specify returnDelims as false.
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html

Categories

Resources