Split string into n parts, separated by dashes [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to split a string s into n parts, separated by dashes. This is the function:
public String answer (String s, int n){}
For example, this should happen:
Example test: ('2-4A0r7-4k', 4)
expect 24A0-R74K
Example test: ('2-4A0r7-4k', 3)
expect 24-A0R-74K
I did this but it gives the wrong answer:
String[] arr = s.split("-", k+1);
s = Arrays.toString(arr);
return s;
It splits starting from the end.

public static String split(String str, int n) {
final Function<String, String> reverse = s -> new StringBuilder(s).reverse().toString();
String[] parts = reverse.apply(str.replaceAll("-", "")).split("(?<=\\G.{" + n + "})");
return IntStream.range(0, parts.length).mapToObj(i -> reverse.apply(parts[parts.length - i - 1])).collect(Collectors.joining("-"));
}

Related

Hide characters after certain index with symbols [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I understand that I did a lot of hard coding that can be avoided so if anything can share their thought please go ahead:
private String hideEmailCharacters(String privateEmail){
String emailName = privateEmail.substring(0,privateEmail.indexOf("#"));
StringBuilder stringBuffer = new StringBuilder(emailName);
stringBuffer.replace(emailName.length() / 2,emailName.length(), StringUtils.repeat("*", emailName.length() / 2));
String emailProvider = privateEmail.substring(privateEmail.indexOf("#"));
return stringBuffer + emailProvider;
}
The goal is to cover for example half of the email name or cover everything after the second character with stars ** so the result from abcdv#example.com would be ab***#example.com
String processing is cool but here's a solution with Regular Expression.
(?<=.{2}).(?=[^#]*?#)
Intuition:
Ignore first 2 characters from the characters before #
Ignore # as well.
Replace each character between with *
public class TestCode {
private static String hideEmailCharacters(String privateEmail) {
return privateEmail.replaceAll("(?<=.{2}).(?=[^#]*?#)", "*");
}
public static void main(String[] args) {
System.out.println(hideEmailCharacters("abcdv#example.com"));
System.out.println(hideEmailCharacters("ra0o29ajzsdc242#example.com"));
System.out.println(hideEmailCharacters("x2helloyouthere#example.com"));
System.out.println(hideEmailCharacters("a#foo.com"));
}
}
Output:
ab***#example.com
ra*************#example.com
x2*************#example.com
a#foo.com
This piece of code will do the trick:
StringBuffer email = new StringBuffer(privateEmail)
int startIndex = email.indexOf("#")/2;
int endIndex = email.indexOf("#");
int numOfCharsToHide = endIndex - startIndex;
email.replace(startIndex, endIndex, "*".repeat(numOfCharsToHide));

Java Program, String [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
It's about string to make a compact output.
Example 1
Input : boooooob
Output : bob
Example2
Input : boobaabbiibbuuuuub
Output : bobabibub
Can anyone help me?
I'm stuck, thx.
This can be solved by using regular expression (\\w)\\1+
public class RemoveReplicateLetter {
public static void main(String[] args) {
//For input: boooooob
System.out.println(removeReplicateLetter("boooooob"));
//For input: boobaabbiibbuuuuub
System.out.println(removeReplicateLetter("boobaabbiibbuuuuub"));
}
public static String removeReplicateLetter(String word) {
/*
REGEX:
(\\w)\\1+
- \\w : matches any word character (letter, digit, or underscore)
- \\1+ : matches whatever was in the first set of parentheses, one or more times.
*/
return word.replaceAll("(\\w)\\1+", "$1");
//Here $1 means return letter with match in word by regex.
}
}
Output:
bob
bobabibub
This method should do the job:
public String simplify(String input) {
// Convert to an array for char based comparison
char[] inputArray = input.toCharArray();
// First char will always be included in the output because there is no char to compete
String output = String.valueOf(inputArray[0]);
// Check every char against the following
for (int i = 1; i < inputArray.length; i++) {
// If not equal
if (inputArray[i - 1] != inputArray[i]) {
// Add to output
output += inputArray[i];
}
}
// Return the result
return output;
}
It will compare every char with the following one and only adds it to the output if they are not equal.
Note: This is just a proof of concept, not an optimal solution.

String to int parseInt [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to convert a string to an int but i take an error. Here is my code:
int foo = Integer.parseInt(ABoard[first]);
if (computerBoard[foo] != -1) {
second = computerBoard[foo];
} else {
second = board.getRandomPosition();
while (first==second) {
second = board.getRandomPosition();
}
}
I want to take a number (int) from a string array and then to take the value of this number from an int array if the value of this number isn't -1.
You need to trim off all of the whitespaces before you parse,
int foo = Integer.parseInt(ABoard[first].trim());
Or replace all non numeric digits
int foo = Integer.parseInt(ABoard[first].replaceAll("[^0-9\\-]", ""); //including 0-9 and -
In order to parse String to int you need to remove all non-numeric characters from it (assuming we are not interested in negative integers).
Here is the code to do that:
int foo = Integer.parseInt(ABoard[first].replaceAll("[^0-9]", ""));

How to substract two strings [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have started learning Java and have some across some difficulties. I'm trying to subtract two strings.
for example, with these strings;"032"&&"100". I want to be able to subtract each number individually so that the answer would be "032".
I have tried using substring, and parsing the two values to ints, but don't know what to do next. I have also tries using a for loop, to go through each arrays of the strings.
I do not expect for anyone to do this for me, but I would love to get some insight,or to tell me that i'm headed in the right direction
thanks
public static String appliquerCoup( String combinaison, String coup ) {
String nouveauCoup="";
if(combinaison!=null&&coup!=null){
for(int i=0;i>combinaison.length();i++){
int a = Integer.parseInt(combinaison.substring(i, i + 1));
int b = Integer.parseInt(coup.substring(i, i + 1));
nouveauCoup=String.valueOf(a-b);
if(a-b<0){
nouveauCoup=0;
}
}
} // main
return nouveauCoup;
}
If I understand you question correctly. you want to subtract each digit individually.
So (0-1), (3-0), (2-0). The following program does this (yields -132):
public static void main(String[] args) {
String A = "032";
String B = "100";
String str = "";
for(int i = 0; i < A.length(); i++)
{
int a = Integer.parseInt(A.substring(i, i + 1));
int b = Integer.parseInt(B.substring(i, i + 1));
int c = a - b;
str += String.valueOf(c < 0 ? 0 : c);
}
System.out.println(str);
}
Essentially, extract the i-th character of each string, convert them to integers, then do the subtraction. Convert the result back to a string and append it to the result string.

how to create array from string in java with respective data items [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How to create an array from a string with two respective data items.
String str="USA*2*Japan*8^2*India*5^4^2*Germany*5*";
Here, I want to create an array of two items in .
Like this:
Arraylist<string> arr= [USA*2,Japan*8^2, India*5^4^2,Germany*5];
Here * is indicating main items and ^ is indicating sub items.
You are using the * to separate "main items" but it can also be inside the main item.
Your requirements look odd, but lets assume for the sake of argument that you are getting your input data like this and you want to split it like you suggested.
That means that every * that is preceded by a number is a separator, but a * that is not preceded by a number is not.
You can achieve that using regular expressions: (with a positive look-behind expression (?<=expr)
String str = "USA*2*Japan*8^2*India*5^4^2*Germany*5";
List<String> lst = Arrays.asList(Pattern.compile("(?<=\\d)\\*").split(str));
System.out.println(lst);
Prints:
[USA*2, Japan*8^2, India*5^4^2, Germany*5]
After further clarification in the comment below, it seems that the problem is more generic than the initial example; the question becomes:
How do I split a string on a separator, but only after 2 occurrences
of the separator.
Although it's possible to do with a regex, it may be easier to do and understand in a for loop like this:
public static List<String> split(String str, char splitChar, int afterOccurrences) {
List<String> lst = new ArrayList<>();
int occurrencesSeen = 0;
int start = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == splitChar) {
occurrencesSeen++;
if (occurrencesSeen >= afterOccurrences) {
lst.add(str.substring(start, i));
start = i + 1;
occurrencesSeen = 0;
}
}
}
if (start < str.length() - 1)
lst.add(str.substring(start));
return lst;
}
public static void main(String[] args) {
String str = "USA*2*Japan*8^2*India*5^4^2*Germany*5";
System.out.println(split(str, '*', 2));
}
This method also allows you to split after 3 or any other number of occurrences.

Categories