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.
Related
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 am currently working on a task and I have a question about the Substring method.
For the task I need to get the first Char of a String and delete the first Char after I used it.
The Strings are names and at the end I only want to have "" an empty String left.
My approach:
String name = "Paul";
char chr = name.charAt(0);
String newName = name.substring(1);
My questions: When I am at the last char "l" and use my substring do I get "" or an error?
My questions: When I am at the last char "l" and use my substring do I
get "" or an error?
You will get a blank string. It is also mentioned in the following lines of documentation:
Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
When you have only l left in the string, its length will be 1 which is perfectly acceptable as the beginIndex. You can also verify it as follows:
public class Main {
public static void main(String[] args) {
System.out.println("l".substring(1));
}
}
To make sure that is error free, do the following.
String name = "Paul";
int nameLength = name.length();
for (int i = 0; i < nameLength; i++){
char chr = name.charAt(0);
if (i != nameLength - 1){
String newName = name.substring(1);
name = newName;
} else {
name = "";
}
}
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
Title. I'm new to this site sorry if it's bad question. I'm trying to make it so that my method returns -1 if there isn't an alphabetical letter in the string. I already set up a way to iterate through the string but now I need to know how to see if it returns true if it finds ANY alphabetical letter in the string and -1 if not.
To find the index of the first letter in a string, use a regular expression:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
static int indexOfLetter(String input) {
String regex = "[a-zA-Z]";
// or: "\\p{Alpha}"; // same as [a-zA-Z]
// or: "\\p{L}"; // all unicode letters
Matcher m = Pattern.compile(regex).matcher(input);
if (m.find())
return m.start();
return -1;
}
Test
System.out.println(indexOfLetter("123456789")); // prints: -1
System.out.println(indexOfLetter("12345ABCD")); // prints: 5
System.out.println(indexOfLetter("##$XYZ%^&")); // prints: 3
If you use the \p{L} regex, it'll find accented letters too.
static int indexOfLetter(String input) {
Matcher m = Pattern.compile("\\p{L}").matcher(input);
return (m.find() ? m.start() : -1);
}
Test
System.out.println(indexOfLetter("...ñ...")); // 3 'LATIN SMALL LETTER N WITH TILDE' (U+00F1)
System.out.println(indexOfLetter("..ß..")); // 2 'LATIN SMALL LETTER SHARP S' (U+00DF)
System.out.println(indexOfLetter(".Δ.")); // 1 'GREEK CAPITAL LETTER DELTA' (U+0394)
UPDATE
If you're not allowed to use regex ("not allow me to use additional import statements"), a simple search loop calling Character.isLetter will do:
static int indexOfLetter(String input) {
for (int i = 0; i < input.length(); i++)
if (Character.isLetter(input.charAt(i)))
return i;
return -1;
}
That does support Unicode letters, but not surrogate pairs. Given the rarity of letters outside the Basic Multilingual Plane (BMP), that's probably not an issue. If it is, the following change will support those too:
static int indexOfLetter(String input) {
for (int i = 0; i < input.length(); i = input.offsetByCodePoints(i, 1))
if (Character.isLetter(input.codePointAt(i)))
return i;
return -1;
}
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
Given a string of integers how to find out all the possible words that can made out of it in continuous order. Eg: 11112
ans: AAAAB
AKAB
AAKB
AAAL etc.
public static void main(String[] args) {
String str="11111124";
char strChar[]=str.toCharArray();
String target="";
for(int i=0;i<strChar.length;i++)
{
target=target+(char)Integer.parseInt(""+(16+strChar[i]));
}
System.out.println(target);
}
i am trying to find the solution for this but not able to find all combination
Combining the comments saying that 163 can be 1,6,3 or 16,3, but not 1,63, and user3437460's suggestion of using recursion:
Take first digit and convert to letter. Make recursive call using letter and remaining digits.
Take first two digits. If <=26, convert to letter and make recursive call using letter and remaining digits.
Here is the code. Since I have no clue what to call the method, I'm going with x.
public static void main(String[] args) {
x("11112", "");
System.out.println("------");
x("163", "");
}
private static final void x(String digits, String word) {
if (digits.isEmpty())
System.out.println(word);
else {
int num = Integer.parseInt(digits.substring(0, 1));
x(digits.substring(1), word + (char)('A' + num - 1));
if (digits.length() >= 2 && (num = Integer.parseInt(digits.substring(0, 2))) <= 26)
x(digits.substring(2), word + (char)('A' + num - 1));
}
}
Output
AAAAB
AAAL
AAKB
AKAB
AKL
KAAB
KAL
KKB
------
AFC
PC
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Have a scenario to strip the below pattern strings -
abc|hjdj|kleygag|0|0|0|0|
ghys|jkugb|0|0|0
yuubf|kluygb|tyrffv|nutgv|0|0|0|0|0|
Looking for help to get a regex in java to separate these values excluding everything from the first occurence of pipe before 0, the output should look like-
abc|hjdj|kleygag
ghyd|jkugb
yuubf|kluygb|tyrffv|nutgv
Just need regex, which has been answered and been very helpful, would just be very helpful to know just the regex and not the complete code for the reverse pattern as requested in the followup question
Is regex necessary for this? substring() gets you want you want easily.
Update
I saw a comment where you're also wanting a case where the data looks like, "0|0|0|0|abdc|ghyft|rtyu". I've modified my answer to account for that case and a case where the data could be, "0|0|0|0|abdc|ghyft|rtyu|0|0|0|"
Either way:
public static void main(String[] args) throws Exception {
List<String> strings = new ArrayList(){
{
add("abc|hjdj|kleygag|0|0|0|0|");
add("ghys|jkugb|0|0|0");
add("yuubf|kluygb|tyrffv|nutgv|0|0|0|0|0|");
add("0|0|0|0|abdc|ghyft|rtyu");
add("0|0|0|0|abdc|ghyft|rtyu|0|0|0|0|0|");
}
};
// Non Regex
System.out.println("Non Regex");
for (String string : strings) {
int startIndex = -1;
int endIndex = -1;
// Find first non zero character
for (int i = 0; i < string.length(); i++) {
if ('a' <= string.charAt(i) && string.charAt(i) <= 'z') {
startIndex = i;
break;
}
}
// Find first pipe zero |0 after startIndex
endIndex = string.indexOf("|0", startIndex);
// Determine which substring() to use based on the endIndex results
System.out.println(endIndex > -1 ? string.substring(startIndex, endIndex) : string.substring(startIndex));
}
System.out.println("");
// Regex
System.out.println("Regex");
for (String string : strings) {
System.out.println(string.replaceAll("\\|0|0\\||\\|$", ""));
}
}
Results:
Non Regex
abc|hjdj|kleygag
ghys|jkugb
yuubf|kluygb|tyrffv|nutgv
abdc|ghyft|rtyu
abdc|ghyft|rtyu
Regex
abc|hjdj|kleygag
ghys|jkugb
yuubf|kluygb|tyrffv|nutgv
abdc|ghyft|rtyu
abdc|ghyft|rtyu
You can use a regex like this:
\|0|0\||\|$
Java code:
String regex = "\\|0|0\\|\\|$";
System.out.println("abc|hjdj|kleygag|0|0|0|0|".replaceAll(regex, ""));
System.out.println("ghys|jkugb|0|0|0".replaceAll(regex, ""));
System.out.println("yuubf|kluygb|tyrffv|nutgv|0|0|0|0|0|".replaceAll(regex, ""));
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.