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 last year.
Improve this question
I am looking for solution using stream api for below requirement. basically we need to write a encryption logic to convert a string
aaabbbbaae --> a3b4a2e1
Solution without stream's api :
public static void main(String[] args) {
String sampleString = "aaabbbaaaaaee";
char charters[] = sampleString.toCharArray();
char currentChar = charters[0];
char prevChar = charters[0];
int count = 0;
String str = "";
for (char c : charters) {
if(c==currentChar) {
count++;
prevChar = c;
}
else {
str = str + prevChar + count;
currentChar = c;
count=1;
}
}
System.out.println(str+currentChar+count);
}
This would be pretty easy to do yourself
String encryptToLettersAndNumbers(String input) {
String product = "";
char last = input.charAt(0);
int streak = 0;
for(int i = 0; i < input.length(); i++) {
if(input.charAt(i) == last) {
streak++;
} else {
product = product + last + streak;
streak = 1;
last = input.charAt(i);
}
}
product = product + last + streak;
return product;
}
Note that this code is untested. Furthermore this will be a very unsafe method of encryption because h1e1l2o1 is pretty easy to guess.
This should get you started-
String sampleString = "aaabbbaaaaaee";
Arrays.asList(sampleString.chars().mapToObj(c->(char)c).toArray(Character[]::new)).stream().forEach(c->{
//You can put your logic here to process
System.out.print(c);
});
This will convert your String to a Character list and stream through it.
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 last month.
Improve this question
I've written a method that is intended to remove characters from a string which are specified by another string.
I'll show you what I've written first so it becomes easier to comprehend my issue:
public static String removeFromInventory(String input, String inventory) {
for (int i = 0; i < input.length(); i++) {
char character = input.charAt(i);
for (int j = 0; j < inventory.length(); j++) {
if (inventory.charAt(j) == character) {
inventory = inventory.replace(character, ' ');
break;
}
}
}
for (int i = 0; i < input.length(); i++) {
if (inventory.charAt(i) == ' ') {
inventory = inventory.replaceAll("\\s+","");
}
}
return inventory;
}
Imagine my input String looks like this: "11+" and my inventory String like this: "111234++". Now what I want to achieve is the following: I want to remove "11+" from the inventory string, so it looks like this afterwards: "11234+".
My code obviously removes any occurrence of the characters in the string. The the return statement looks like this after going through the function: "234".
If you know how I could implement some logic to only remove the first occurrence of the character I would greatly appreciate it. Thanks for any help in advance!
Solution 1:
The function iterates through each character of the "input" string in a loop and utilizes the String.replaceFirst() method and a regular expression pattern constructed with Pattern.quote to replace the "+" has a special meaning in regex, so it needs to be escaped/quoted. The function's output is then the resultant "inventory" string without the given characters. By doing this, it will eliminate every occurrence of the characters from the inventory string. As anticipated, the final result is "1234+".
public static String removeChars(String input, String inventory) {
for (int i = 0; i < input.length(); i++)
inventory = inventory.replaceFirst(Pattern.quote(String.valueOf(input.charAt(i))), "");
return inventory;
}
Solution 2:
The second solution is more optimized as it uses a HashMap to store the count of characters in the input, so it can handle the case of removing characters in input multiple times. It also uses StringBuilder for building the final string, which is more efficient than concatenating strings.
public static String removeCharacters(String input, String inventory){
StringBuilder sb = new StringBuilder();
HashMap<Character, Integer> inputCount = new HashMap<>();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
inputCount.put(c, inputCount.getOrDefault(c, 0) + 1);
}
for (int i = 0; i < inventory.length(); i++) {
char c = inventory.charAt(i);
if (!inputCount.containsKey(c) || inputCount.get(c) == 0) {
sb.append(c);
} else {
inputCount.put(c, inputCount.get(c) - 1);
}
}
return sb.toString();
}
The documentation for the method says
"Returns a string resulting from replacing all occurrences of oldChar in this string with newChar."
https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/String.html#replace(char,char)
substring would be an OK replacement if used like this.
for (int j = 0; j < inventory.length(); j++) {
if (inventory.charAt(j) == character) {
inventory = inventory.substring(0,j) + ' ' + inventory.substring(j+1);
break;
}
}
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 last year.
Improve this question
I was doing a few beginner coding challenges and one of the challenge was making a program that reverses a given String. It worked on words, but as soon as I put in words with spaces between them the program only reversed the first word entered.
I googled "reverse words with spaces in it java" and found this:
// Java program to reverse a string
// preserving spaces.
public class ReverseStringPreserveSpace {
// Function to reverse the string
// and preserve the space position
static void reverses(String str)
{
char[] inputArray = str.toCharArray();
char[] result = new char[inputArray.length];
// Mark spaces in result
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] == ' ') {
result[i] = ' ';
}
}
// Traverse input string from beginning
// and put characters in result from end
int j = result.length - 1;
for (int i = 0; i < inputArray.length; i++) {
// Ignore spaces in input string
if (inputArray[i] != ' ') {
// ignore spaces in result.
if (result[j] == ' ') {
j--;
}
result[j] = inputArray[i];
j--;
}
}
System.out.println(String.valueOf(result));
}
// driver function
public static void main(String[] args)
{
reverses("internship at geeks for geeks");
}
}
Why were char arrays used instead of String directly?
Can I modify my own code to make it reverse a sentence without following the above code?
My code:
import java.util.Scanner;
class ReverseString
{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the word to be reversed:");
String input = s.next();
String reversed = "";
for (int i = 0; i < input.length(); i++)
{
char ch = input.charAt(i);
reversed = ch + reversed;
}
System.out.println(reversed);
}
}
The solution that you found above was a highly over engineered solution to a very simple problem.
Sometimes its better to use char arrays when performing operations on strings because it might increase performance. Strings in java are immutable and every time you mutate a String a new String object is created. So char array can be used to increase the performance of the code.
Your code is working fine with sentences when I checked it. I don't really know what issue you are facing.
Edit : You should avoid using scanner.next(); method when taking an input string. Because it only read the string up until a space. Therefore your program is not reading the entire string that you entered.
You should instead use scanner.nextLine(); for reading a String value.
For more info on Scanner class : http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
This is a pretty good way of Reversing a String. This probably the most efficient way of reversing a String.
public String reverseString(String input) {
char[] arr = input.toCharArray();
int i = 0, j = arr.length - 1;
while(i < j) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++; j--;
}
return new String(arr);
}
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
I want to eliminate vowels from a String, I can eliminate them, but I fail to return them to main(). I got the exact output by using the following code.
String string = "ajeIokluj";
String s = string.replaceAll("[aeiouAEIOU]","");
return s;
It will be great if the required output came by using for loop.
Hope you have written the code similar to below considering your fail to return statement .
public static void main(String[] args) {
String string = "ajeIokluj";
String s = eliminateVowels(string);
System.out.println(s);
}
private static String eliminateVowels(String string) {
String s = string.replaceAll("[aeiouAEIOU]","");
return s;
}
If you did it works perfectly fine and if not use above as reference ;)
Based on your comments since you looking for specifically using for loop (Which is not recommended) please find code below.
public static String removeVowels(final String string){
final String vowels = "AaEeIiOoUu";
final StringBuilder builder = new StringBuilder();
for(final char c : string.toCharArray())
if(vowels.indexOf(c) < 0)
builder.append(c);
return builder.toString();
}
public class main {
public static String removeVowels(String word) {
String ret = "";
String realRet = "";
for (int i = 0; i < word.length(); i++) {
if ("aeiouAEIOU".indexOf(word.charAt(i)) == -1) {
ret += word.charAt(i);
}
}
realRet = realRet + ret.charAt(0) + ret.charAt(1);
return realRet.toLowerCase() ;
}
public static void main(String[] args) {
String pass = removeVowels("Your String");
for(int i=0 ; i < 3; i++) {
pass = pass + (int) (Math.random() * 100) ;
}
System.out.println(pass);
}
}
Try this it may work you!!
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
I need to increment by one an String that is only digits:
String current = "000433"; //After increment, will be "000434"
I have this procedure, that works properly:
private String incrementOne(String numberAsString) {
int leftZeroCount = countLeadingZeros(numberAsString);
Integer asInteger = Integer.parseInt(numberAsString);
asInteger++;
return parseStringWithNZeros(asInteger, leftZeroCount);
}
private String parseStringWithNZeros(Integer asInteger, int leftZeroCount) {
String asString = Integer.toString(asInteger);
for (int i = 0; i < leftZeroCount; i++)
asString = "0" + asString;
return asString;
}
private int countLeadingZeros(String numberAsString) {
int count = 0;
int i = 0;
while (numberAsString.charAt(i) == '0' && i < numberAsString.length()) {
count++;
i++;
}
return count;
}
The process is:
Count the left zeros
Parse to Integer
Increment by one
Parse to String
Add the left zeros
The length of the number as String is unknown. I am sure that exists another easier and cleaner way, with regex or something. Which alternatives can I adopt?
Thanks.
How about doing it like this, using String.format():
String original = "000433";
String incremented = String.format("%0" + original.length() + "d",
Integer.parseInt(original) + 1);
System.out.println(incremented);
Try this:
private String incrementOne(String numberAsString) {
int length = numberAsString.length();
Integer asInteger = Integer.parseInt(numberAsString);
asInteger++;
numberAsString = asInteger.toString();
while(numberAsString.length() < length){
numberAsString = "0" + numberAsString;
count ++;
}
return numberAsString;
}
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 8 years ago.
Improve this question
import java.util.StringTokenizer;
public class PigLatins {
String str1;
int vowelIndex;
String[] vowels = {"a","e","i","o","u","A","E","I","O","U"};
String counter = "";
public String pigLatin(String str) {
String[] result = str.split("\\s");
for (int x=0; x<result.length; x++) {
for(int i = 0;i<vowels[i].length();i++) {
if(!result[x].contains(vowels[i])) {
str1 = result[x]+"ay";
}
else if(result[x].startsWith(vowels[i])) {
str1 = result[x]+"ay";
}
for(int j = 0;j<result[x].length();j++)
if(Character.toString(result[x].charAt(j)) == vowels[i]) {
vowelIndex = j;
break;
}
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i])) {
str1 = result[x].substring(1,vowelIndex) + result[x].substring(0,1) + "ay";
}
}
counter+=str1;
}
return counter;
}
}
At this part result[x].substring(1,vowelIndex) in the if statement, it seems to return null, why is it wrong and how could I fix it? (I removed the driver class as stackoverflow told me to I had too much code)
You should change :
for(int i = 0;i<vowels[i].length();i++)
to
for(int i = 0;i<vowels.length;i++)
Since you want to iterate over all the vowels in the array.
vowels[i].length() will always give you 1, since it's the length of the i'th String in the vowels array.
Beside that, it would make more sense to change the vowels array from String[] to char[].
the problem here is that the vowelIndex is 0 while you start in index 1 for the substring.
i don't quite understand what you are trying to achive but you need to check in you if statement the value of vowelIndex:
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i]))
the whole function should be
public String pigLatin(String str) {
String[] result = str.split("\\s");
for (int x=0; x<result.length; x++) {
for(int i = 0;i<vowels[i].length();i++) {
if(!result[x].contains(vowels[i])) {
str1 = result[x]+"ay";
}
else if(result[x].startsWith(vowels[i])) {
str1 = result[x]+"ay";
}
for(int j = 0;j<result[x].length();j++)
if(Character.toString(result[x].charAt(j)) == vowels[i]) {
vowelIndex = j;
break;
}
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i])) {
str1 = result[x].substring(1,vowelIndex) + result[x].substring(0,1) + "ay";
}
}
counter+=str1;
}
return counter;
}
also you should not use an array of strings of you need an array of charecters, or if i understand correctly you should use a set of charecters