Splitting string into an array - java

I am attempting to split the components of a string into an array, so that they can be accessed more easily.
For example: 4+5= should become ['4','+','5','='].
Edit: -
I would need consecutive numbers to be joined together, and whitespaces can be ignored. Thanks again!

You can solve it with regex lookaround mechanism.
String str = "10 * 10 - 40 + 100/2 = 110";
//but first lets remove white spaces (it will makes regex easier)
String strWithoutSpaces=str.replaceAll("\\s+", "");
String[] tokens = strWithoutSpaces.split("(?<=[-+*/=])|(?=[-+*/=])");
for (String t:tokens)
System.out.print(t+",");
Output:
10,*,10,-,40,+,100,/,2,=,110,

You can use
String str = "4+5=";
String[] tokens = str.split("(?!^)");
for (String s : tokens) {
System.out.println(s);
}
This will output
4
+
5
=

You could use toCharArray() method
String s ="4+5=";
char [] stArr = s.toCharArray();
for(char ss: stArr){
System.out.println(ss);
}
Out put
4
+
5
=

You could do something like this:
public static void main(String args[]) {
String str = "45+5-26";
String strArr[] = new String[str.length()];
StringBuffer sb = new StringBuffer();
int cnt = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != '\0') {
if (ch == ' ') {
continue;
}
if (ch >= 48 && ch <= 57) {
sb.append(ch);
continue;
} else {
strArr[cnt++] = sb.toString();
sb = new StringBuffer();
// sb.append(ch);
}
strArr[cnt++] = ch + "";
sb = new StringBuffer();
}
}
strArr[cnt++] = sb.toString();
sb = new StringBuffer();
System.out.println("strArray: ");
for (int i = 0; i < strArr.length; i++) {
if (strArr[i] == null)
break;
System.out.println(strArr[i]);
}
}
If you have only operators as the separator between the numbers this would be more easy to get the string tokens.
You can modify as below if you want the tokens separated by a comma:
for (int i = 0; i < strArr.length; i++) {
if (strArr[i] == null)
break;
// System.out.println(strArr[i]);
if(i!=0)
sbResult.append(",");
sbResult.append(strArr[i]);
}
System.out.println("sbResult: "+sbResult.toString());

Related

Replacing the number with the number of spaces

I have a String:
String example = "AA5DD2EE3MM";
I want to replace the number with the number of spaces. Example:
String example = "AA DD EE MM"
If the String would be
String anotherExample = "a3ee"
It should turn into:
String anotherExample = "a ee"
I want to do it for any string. Not only for the examples above.
Split your input at digit and non digit chars as a stream, map digits to the corsponding number of spaces using String.repeat, collect to string using Collectors.joining():
String input = "AA5DD2EE3MM";
String regex = "(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)";
String result = Pattern.compile(regex)
.splitAsStream(input)
.map(s -> s.matches("\\d+") ? " ".repeat(Integer.parseInt(s)) : s)
.collect(Collectors.joining());
You could also use this approach, which is simpler but also far less elegant:
String example = "a4aa";
String newString = "";
for (int i = 0; i < example.length(); i++) {
if (Character.isDigit(example.charAt(i))) {
for (int a = 0; a < Character.getNumericValue(example.charAt(i)); a++) {
newString += " ";
}
} else {
newString += example.charAt(i);
}
}
System.out.println(newString);
Using a pattern matcher approach:
String input = "AA5DD2EE3MM";
Pattern pattern = Pattern.compile("\\d+");
Matcher m = pattern.matcher(input);
StringBuffer buffer = new StringBuffer();
while (m.find()) {
m.appendReplacement(buffer,new String(new char[Integer.valueOf(m.group())]).replace("\0", " "));
}
m.appendTail(buffer);
System.out.println(buffer.toString()); // AA DD EE MM
The idea here is to iterate the string, pausing at each digit match. We replace each digit with space replicated the same number of times as the digit.
public static String replaceDigitsWithSpaces(String input) {
String result = "";
int len = input.length(), i =0;
while( i < len) {
if(Character.isLetter(input.charAt(i))) {
result += input.charAt(i);
}else if(Character.isDigit(input.charAt(i))) {
//generate number upto characters
int k = 0, j = i;
String temp = "";
while(j < len) {
if(Character.isDigit(input.charAt(j))) {
temp += input.charAt(j);
j++;
}else {
break;
}
}
k = Integer.parseInt(temp);
while(k != 0) {
result+= " ";
k--;
}
i = j;
continue;
}
i++;
}
return result;
}
input:: "AA23BB1C11C8"<br>
output:: AA BB C C .
StringBuilder is more efficient for concatenation:
public static String spaceIt(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
for (int j = 0; j < Character.digit(c, 10); j++) {
sb.append(' ');
}
} else {
sb.append(c);
}
}
return sb.toString();
}

A simple decryption in Java

I am writing a method to decrypt a input string. The encryption is straight forward. Any repeating character in the string is replaced by the character followed by the number of times it appears in the string. So, hello is encrypted as hel2o. Below is the decryption logic I have so far. It works but is so imperative and involves multiple loops. How can this be improved?
String input = "hel2o";
String[] inarr = input.split("\\s+");
StringBuilder sb = new StringBuilder();
for(int i = 0; i < inarr.length; i++) {
String s = inarr[i];
char[] c = s.toCharArray();
for(int j = 0; j < c.length; j++) {
if(Character.isDigit(c[j])) {
for(int x = 0; x < Character.getNumericValue(c[j])-1; x++) {
sb.append(c[j-1]);
}
} else {
sb.append(c[j]);
}
}
}
System.out.printl(sb.toString());
You pretty much asked for a solution but I had fun doing it so I'll share.
You can do it with one loop, by doing some clever appending. Also, unlike yours, my solution will work with multi digit numbers e.g.
Hel23o will convert to helllllllllllllllllllllllo with 23 l's.
String input = "hel23o";
StringBuilder builder = new StringBuilder();
char previousChar = ' ';
StringBuilder number = new StringBuilder();
for (char c : input.toCharArray()) {
if (Character.isDigit(c)) {
number.append(c);
continue;
}
if (number.length() > 0 ) {
int count = Integer.parseInt(number.toString());
count = count > 1 ? count - 1 : 0;
builder.append(String.join("", Collections.nCopies(count, String.valueOf(previousChar))));
}
builder.append(c);
previousChar = c;
number.setLength(0);
}
Alternatively without the multi digit number support:
String input = "hel3o";
StringBuilder builder = new StringBuilder();
char previousChar = ' ';
for (char c : input.toCharArray()) {
if (Character.isDigit(c)) {
builder.append(String.join("", Collections.nCopies(Character.getNumericValue(c) - 1, String.valueOf(previousChar))));
continue;
}
builder.append(c);
previousChar = c;
}

How do i Reverse Capitalize And Separate Words By Line Using String In Java?

The input is: i love cake
The output needs to be: Cake Love I
But the actual result is: I Love Cake
What I've got:
import java.util.regex.Pattern;
public class yellow {
static String reverseWords(String str){
Pattern pattern = Pattern.compile("\\s");
String[] temp = pattern.split(str);
String result = "";
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1)
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
}
public static void main(String[] args){
String source = "i love cake";
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print(res.toString());
}
}
What am I doing wrong?
for (String str : strArr) {
}
This loops forward. What you want is to loop backwards, or to place elements into the string backwards. I recommend you loop backwards and print as you go:
for (int i = strArr.length - 1; i >= 0; i--) {
char[] stringArray = strArr[i].trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
System.out.println(new String(stringArray));
}
Or, you could use that convenient reverseWords method that you never use anywhere... though looping backwards is faster. Probably.
[EDITED]
Call this for each line with string s, then print a line break (If you have multiple sentences & expect them in their own lines).
void reverseCamel(String s){
String[] ar = s.split("\\s+");
for(int i = ar.length - 1;i>=0;i--){
ar[i][0] = Character.toUpperCase(ar[i][0]);
System.out.print(ar[i] + " ");
}
}
Here is what i did.
public class Main {
public static void main(String[] args) {
reverse("I Love Cake");
}
public static void reverse( String string){
String[] word =string.split(" "); // split by spaces
int i = word.length-1;
while (i>=0){
// System.out.print(word[i].toUpperCase()+" ");//if you want in upper case
System.out.print(word[i]+" ");
i--;
}
}
}
First of all you have to reverse the String.
String[] words = source.split("\\s");
String reversedString = "";
for(int i = words.length -1; i>=0; i--){
reversedString += words[i] + " ";
}
Then, you know that the ASCII code of 'a' character is 97, 'A' is 65. To convert from lower case to capital you substract 32. All capitals are between 65 and 92. All small letters are between 97 and 124.
You want to capitalize only letters at the beginning of a word (preceded by a space or first letter).
String capitalCase = "";
for (int i = 0; i < reversedString.length(); i++) {
char c = reversedString.charAt(i);
if (c >= 97 && c <= 124) {
if (i == 0) c -= 32;
else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
}
capitalCase += c;
}
And here you go now System.out.println(capitalCase);
Overall, you will have the following code:
import java.util.Scanner;
public class yellow {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a string:");
String source = s.nextLine();
String[] words = source.split("\\s");
String reversedString = "";
for (int i = words.length - 1; i >= 0; i--) {
reversedString += words[i] + " ";
}
String capitalCase = "";
for (int i = 0; i < reversedString.length(); i++) {
char c = reversedString.charAt(i);
if (c >= 97 && c <= 124) {
if (i == 0) c -= 32;
else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
}
capitalCase += c;
}
System.out.println(capitalCase);
}
}
Output:
Enter a string:
i love cake
Cake Love I
Java 8 * Apache Commons Lang
public static String reverseWordsInString(String str) {
List<String> words = Pattern.compile("\\s+").splitAsStream(str)
.map(StringUtils::capitalize)
.collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
return words.stream().collect(Collectors.joining(StringUtils.SPACE));
}
Java 8
public static String reverseWordsInString(String str) {
List<String> words = Pattern.compile("\\s+").splitAsStream(str)
.map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase())
.collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
return words.stream().collect(Collectors.joining(" "));
}

Splitting a String with Last Space of Max Characters

I am trying to split a String with a Last space of my max allowed character:
Expectation:
String name = "John David Guetta MarkHenry Anthoney Sam";
Max Character allowed : 30
So it should return as:
John David Guetta MarkHenry
Anthoney Sam
Actual Result:
John David Guetta MarkHenry An
thoney Sam
Code:
public static List<String> splitByLength(String str, int n) {
List<String> returnList = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (i > 0 && (i % n == 0)) {
returnList.add(sb.toString());
sb = new StringBuilder();
}
sb.append(str.charAt(i));
}
if (StringUtils.isNoneBlank(sb.toString())) {
returnList.add(sb.toString());
}
return returnList;
}
You could use a regex that accepts up to 30 characters:
String name = "John David Guetta MarkHenry Anthoney Sam";
Pattern p = Pattern.compile(".{1,30}(\\s+|$)");
Matcher m = p.matcher(name);
while(m.find()) {
System.out.println(m.group().trim());
}
Note the (\\s|$) to break either on a space or once the end of the initial string is reached.
I always find it difficult and troublesome using Regex, so here is a solution that I would use
private static void splitByLength(String str, int n) {
String newStr = "";
int splitIndex = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != ' ') {
newStr = newStr + str.charAt(i); //Keep adding chars until you find a space
if (newStr.length() > n) { //If newStr's length exceeds 'n', break the loop
break;
}
} else {
splitIndex = i; //Store the last space index
newStr = newStr + ' ';
}
}
System.out.println(str.substring(0, splitIndex).trim()); //Use the splitIndex to print a substring
System.out.println(str.substring(splitIndex, str.length()).trim());
}

How to replace odd/even chars in string with spaces in Java?

If given a string like "go to med!" how do I replace just the even characters for example? The problem is that while my code takes care of the first word, the space between the words counts as a character itself and messes up replacements in the second word with the first letter of the second word becoming classified as even.
Here is my attempt
public static void main(String[] args) {
String s = "go to med!";
String alphabetS = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(s);
for(int i=0; i<s.length(); i++){
char currChar = s.charAt(i);
int idx = alphabetS.indexOf(currChar);
if (idx != -1)
if (i%2==1)
{
sb.setCharAt(i, '*');
}
}
System.out.println(sb);
}
This gives output "g+ +o m+d!"
(second letter being correctly replaced by + for being even, but the first letter of the second word should not be replaced as "first" is not "even".
How to make the index to ignore white spaces?
Preferably the answer should not contain arrays, only Char and String methods.
You could simply split the input on the space and process each work individually. You could then use a StringJoiner to piece together the result, for example...
String s = "go to med!!";
String alphabetS = "abcdefghijklmnopqrstuvwxyz";
String[] words = s.split(" ");
StringJoiner sj = new StringJoiner(" ");
for (String word : words) {
StringBuilder sb = new StringBuilder(word);
for (int i = 0; i < sb.length(); i++) {
char currChar = sb.charAt(i);
int idx = alphabetS.indexOf(currChar);
if (idx != -1) {
if (i % 2 == 1) {
sb.setCharAt(i, '*');
}
}
}
sj.add(sb.toString());
}
System.out.println(sj.toString());
which outputs
g* t* m*d!!
could this be done without using arrays - just with char and string methods?
Instead of relying on i, you need a separate counter, which tracks which point your up to and which can be used to ignore invalid characters, for example
String s = "go to med!!";
String alphabetS = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(s);
int counter = 0;
for (int i = 0; i < sb.length(); i++) {
char currChar = sb.charAt(i);
int idx = alphabetS.indexOf(currChar);
if (idx != -1) {
if (counter % 2 == 1) {
System.out.println("!!");
sb.setCharAt(i, '*');
}
counter++;
}
}
System.out.println(sb.toString());
which still outputs
g* t* m*d!!
this gives: g* t* m*d*
public static void main(String[] args) {
String s = "go to med!";
int realindex=0;
StringBuilder sb = new StringBuilder();
for(int i=0; i<s.length(); i++){
char currChar = s.charAt(i);
if ((currChar != ' '))
{
if (realindex%2==1) {
currChar = '*';
}
realindex++;
}
sb.append(currChar);
}
System.out.println(sb.toString());
}
There are a thousand different ways to accomplish your goal, but assuming you want to keep using your solution, here is what you could do
public static void main(String[] args) {
String s = "go to med!! goodbye cruel world";
String alphabetS = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(s);
for (int i = 0,relativePosition=0; i < s.length(); i++,relativePosition++) {
char currChar = s.charAt(i);
if(currChar == ' '){relativePosition=-1;continue;}
int idx = alphabetS.indexOf(currChar);
if (idx != -1)
if (relativePosition % 2 == 1)
sb.setCharAt(i, '*');
}
System.out.println(sb);
}
that prints
g* t* m*d!! g*o*b*e c*u*l w*r*d
What about introducing flag about even state of letter?
boolean isEven=false;
for(int i=0; i<s.length(); i++){
char currChar = s.charAt(i);
int idx = alphabetS.indexOf(currChar);
if (idx != -1)
if(isEven){
isEven=false;
sb.setCharAt(i, '*');
}else {
isEven = true;
}
}
}

Categories