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 6 years ago.
Improve this question
I need to write a java code to covert VBA7425IWC to ABV2457CIW. I need help in that. If I sort the strings they sort by ASCII values and the numbers become one chunk and the alphabets another.
This one uses regex. You may have to adjust the pattern to include lower case letters:
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SplitRegex {
public static void main(String[] args) {
// The search string
String str = "VBA7425IWC";
// The Regular expression (Finds {word} tokens)
Pattern pt = Pattern.compile("[A-Z]+|[0-9]+");
// Match the string with the pattern
Matcher m = pt.matcher(str);
String result = "";
// If results are found
while (m.find()) {
char[] chArray = m.group(0).toCharArray();
Arrays.sort(chArray);
result += new String(chArray);
}
System.out.println(result);
}
}
Your question is a little vague in its requirements. Are you attempting to sort each individual substring of characters and numbers?
In that case, you need to determine the ranges of each substring, denoted by a shift from characters to numbers.
start = 0
current = 0
for current = 0 to string.length-1:
if ASCII of current is letter AND ASCII of next is number OR vice-versa:
sort(string, start, current)
start = current
You can find if a character is a letter or number by its ASCII value.
Here is sample solution which I achive by dividing string intro numeric and alphabetic substrings stored in List and then sorted and reduce with java 8 stream API.
String s = "VBA7425IWC";
List<String> mylist = new ArrayList<>();
StringBuilder subString = new StringBuilder();
for (int k = 0; k < s.length() - 1; k++) {
subString.append(s.charAt(k));
if ((Character.isDigit(s.charAt(k + 1))
&& Character.isAlphabetic(s.charAt(k))) ||
(Character.isDigit(s.charAt(k))
&& Character.isAlphabetic(s.charAt(k + 1)))) {
mylist.add(subString.toString());
subString.setLength(0);
}
}
mylist.add(subString.append(s.charAt(s.length() - 1)).toString());
System.out.println(mylist);
String finalResult = mylist
.stream()
.map((myString) -> {
char[] charArr = myString.toCharArray();
Arrays.sort(charArr);
return new String(charArr);
})
.reduce("", (s1, s2) -> s1 + s2);
Related
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 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 4 years ago.
Improve this question
I want to make a method that returns an ArrayList and takes two arguments, one is a string and other is a character. I want to put in ArrayList all the indexes of the characters if they appear in string argument. For example, if a first parameter is a String "hello" and other is 'l' the Array should contain 2 and 3
Some java code for you:
void Indices(String str, char c){
List<int> list = new ArrayList<>(); // define list
for(int i = 0; i < str.length; i++){ // go through each char in str
if(str.charAt(i) == c){ // if the chars match
list.add(i); // add to list
}
}
return list; // return list
}
Here is a basic example:
class Converter {
public static String convert(String b, char a) {
ArrayList<String> c = new ArrayList<>();
String d = String.valueOf(a);
for(int x = 0; x < b.length(); x++) {
String current = String.valueOf(b.charAt(x));
if(current.equals(d)) {
c.add(String.valueOf(x));
}
}
return c.toString();
}
}
public class ChapterOneBasics{
public static void main(String[] args) throws IOException{
Converter h = new Converter();
System.out.println(Converter.convert("Hello", 'l'));
}
}
What we do here is we create a variable that takes a String argument and a character primitive argument. We then create an empty array list that will take the string value of the index if the index of the String matches the character argument. WE then convert the character to a string. Next, we run a for loop so that we can iterate through each index in the array. We make the current string the value of the character of the that we are iterating through at the moment. If that string equals the string value of the character that we passed to the method as an argument, we add the index (x) to the array list. When our for loop is done, we return that array list. This will return [2, 3] if we pass the string hello as the argument.
I will say this, you SHOULD show your work and attempt to do the problem before posting the question. That will make it easier for us to help you. I explained the problem in detail for you because it is important that you show your work and at least attempt to solve your problem. Then you can learn.
There are a variety of ways you can solve this. One is what #gkgkgkgk provides. Here are two other approaches.
Utilizes a while loop and String.indexOf() as #ElliottFrisch mentions in his comment.
With regex, the pattern you would use would be the character you are looking for.
Code:
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StackOverflow {
public static void main(String args[]) {
String data = "The quick brown fox jumps over the lazy dog";
System.out.println("\'e\' is at indexes" + findIndexesWithWhile(data, 'e'));
System.out.println("\'o\' is at indexes" + findIndexesWithRegex(data, 'o'));
}
public static ArrayList<Integer> findIndexesWithWhile(String data, char character) {
ArrayList<Integer> indexes = new ArrayList<Integer>();
int index = 0;
while (index != -1) {
index = data.indexOf(character, index);
if (index != -1) {
indexes.add(index);
index++;
}
}
return indexes;
}
public static ArrayList<Integer> findIndexesWithRegex(String data, char character) {
ArrayList<Integer> indexes = new ArrayList<Integer>();
Pattern pattern = Pattern.compile(String.valueOf(character));
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
indexes.add(matcher.start());
}
return indexes;
}
}
Result:
'e' is at indexes[2, 28, 33]
'o' is at indexes[12, 17, 26, 41]
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.
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.