Inject character between substring of a string in Java [closed] - java

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 have a list of words stored in a list, words.
private String[] words = new String[]{"world", "you"};
I then have a string, helloWorld
private String helloWorld = "Hello world how are you?";
I would like to create a function that will take a string (in this case, helloWorld) and it will look case-insensitively to see if any of the strings in the words list are present. If there is, it will put a * character in between each letter of the matching string.
E.g. the output would be
Hello w*o*r*l*d how are y*o*u? since both world and you are in the list.
Passing "Hello" would simply return back the unmodified string "Hello" because there is nothing in the string that is inside words.
How would I go about doing this? I have tried hardcoding a .replaceAll() call on the string for each word, but then I lose the casing of the string. E.g. "Hello world how are you?" became "hello w*o*r*l*d how are y*o*u?"

This code:
private static String[] words = new String[]{"world", "you"};
private static String helloWorld = "Hello world how are you?";
public static String getHello() {
String s = helloWorld;
for (String word : words) {
int index = s.toLowerCase().indexOf(word.toLowerCase());
if (index >= 0) {
String w = s.substring(index, index + word.length());
StringBuilder sb = new StringBuilder();
sb.append(s.substring(0, index));
for (int i = 0; i < w.length(); i++) {
sb.append(w.charAt(i));
if (i < w.length() - 1)
sb.append("*");
}
sb.append(s.substring(index + w.length()));
s = sb.toString();
}
}
return s;
}
public static void main(String[] args) {
System.out.println(getHello());
}
prints:
Hello w*o*r*l*d how are y*o*u?

String helloWorld = "hello world how are you ";
String[] words = new String[]{"world", "you"};
String newWord = "";
String words1[]= helloWorld.split(" ");
for (int i = 0;i< words.length;i++){
for (int j=0;j<words1.length;j++){
if (words1[j].equals(words[i])){
for (int k = 0 ; k < words1[j].length(); k++){
char character = words1[j].charAt(k);
newWord+=character;
newWord += "*";
}
words1[j] = newWord;
newWord= "";
}
}
}
String str = Arrays.toString(words1);
System.out.println(str);
}

Related

Java basic, reversing a word and how it is achieved through a for loop [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 4 years ago.
Improve this question
I am new towards coding, so I've managed to create a code that allows me to reverse words, however, I don't fully understand the for loop construct, because I created this using online resources.
public class word {
public static String rWords(String input) {
String[] split = input.split("");
String output = " ";
for (int i = split.length - 1; i >= 0; i--) {
output += (split[i] + "");
}
return output.trim();
}
}
Say there is already a main class that contains a string value of input, this is another class called word, I understand that making it public static string means it's public and static means it's not declared in instances. It contains one parameter with the input from main class, the output is empty for my for loops results to go into that, however, how does the for loop allow my input to be reversed and return.trim do?
Why don't you use out-of-box approach? E.g. StringBuilder already has a method reverse():
public static String reverseWords(String str) {
return Arrays.stream(str.trim().split("\\s+"))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
}
But you string can do it with old Java:
public static String reverseWords(String str) {
// using StringBuilder for multiple string concatenation
StringBuilder buf = new StringBuilder(str.length());
for (String word : str.trim().split("\\s+")) {
// add space if word is not first one
if (buf.length() > 0)
buf.append(' ');
// add each word from end to beginning
for (int i = word.length() - 1; i >= 0; i--)
buf.append(word.charAt(i));
}
return buf.toString();
}
In case you need swap words in the sentence, principle is the same:
public static String reverseWords(String str) {
StringBuilder buf = new StringBuilder(str.length());
String[] words = str.trim().split("\\s+");
for (int i = words.length - 1; i >= 0; i--) {
if (buf.length() > 0)
buf.append(' ');
buf.append(words[i]);
}
return buf.toString();
}

Need help printing words in reverse in JAVA [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 5 years ago.
Improve this question
I am having troubles in JAVA. I am trying to get the string to print out backwards for each word.
Example: Hello World would be "olleh dlrow"
Below is my class. thanks for the help.
public class ReadReverse {
String message = "Hello nice to meet you in CS102";
String[] myStrings = message.split(" "); //Makes an array of the words split up by spaces
String result = "";
{
// gets the length of the array and splits it up by each word
for (int i = 0; i < myStrings[i].length(); i++) {
message.push(myStrings[i].at(i));
// sets th length to the length of the word
int length = message.length();
// pops the letter out into the new stack
for (i = 0; i < length; i++) {
result += myStrings;
}
// checks to see if it is at the end of the string.
if (i != message.length() - 1) {
result += " ";
}
}
}
}
You can achieve string reversal in many ways.
Have a look into this :
class ReverseString
{
public static void main(String[] args)
{
String input = "Hello world";
String[] words = input.split(" ");
String reversedString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
reversedString = reversedString + reverseWord + " ";
}
System.out.println(input);
System.out.println(reversedString);
}
}
I would revert word by word in this way:
String input = "Hello world";
String[] words = input.split(" ");
StringBuilder reversed = new StringBuilder(
for (String word : words) {
reversed.append(new StringBuilder(word).reverse())
.append(" ");
}
System.out.println(reversed);
Or using java 8 streams this way :
String input = "Hello world";
StringBuilder reversed = new StringBuilder();
Stream.of(input.split(" "))
.map(StringBuilder::new)
.map(StringBuilder::reverse)
.forEach(word -> reversed.append(word).append(" "));
System.out.println(reversed);
Outputs : olleH dlrow

Trying to replace and reversing the entire Alphabetical order in Java [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 5 years ago.
Improve this question
I am trying to reverse the entire Alphabetical order A-Z --> Z-A.
This is what I have so far.
public class Program {
public static voud main(String[] args) {
String text = "Hi My name is Dave\n";
text = text.replaceAll("[a-z ]",["z-a"]);
System.out.println(text);
This will print out z-a for every letter, which is why I was wondering is there a way to replace every single character from a-z to z-a?
Actually, it's very difficult to develop it using RegEx. I suggest using Stream and Lambda:
String text = "Hi My name is Dave\n";
int[] chars = text.chars()
.map(ch -> Character.isUpperCase(ch) ? 25 - ch + 'A' * 2 :
Character.isLowerCase(ch) ? 25 - ch + 'a' * 2 : ch)
.toArray();
text = new String(chars, 0, chars.length);
System.out.println(text);
And the output is:
Sr Nb mznv rh Wzev
This is a solution in case you are not using Java 8 with streams and Lambdas.
If you want to reverse the order of the characters in your original string ("ABC" ==> "CBA"), try this code:
public static String reverseString(final String original) {
StringBuffer reverse = new StringBuffer();
for (int i = original.length() - 1 ; i >= 0 ; i-- )
reverse.append(original.charAt(i));
return reverse.toString();
}
If you want to replace "A" with "Z", "B" with "Y" and so on ("ABC" ==> "ZYX") try this code:
public static String reverseCharacters(final String original) {
final int UPPERCASE_A = 'A';
final int UPPERCASE_Z = 'Z';
final int LOWERCASE_A = 'a';
final int LOWERCASE_Z = 'z';
StringBuffer reverse = new StringBuffer();
char character = ' ';
for ( int i = original.length() - 1 ; i >= 0 ; i-- ) {
int charInt = original.charAt(i);
if (Character.isUpperCase(original.charAt(i)) {
reverse.append((char)(UPPERCASE_Z - charInt + UPPERCASE_A));
} else if (Character.isUpperCase(original.charAt(i))) {
reverse.append((char)(LOWERCASE_Z - charInt + LOWERCASE_A);
} else {
reverse.append(original.charAt(i));
}
}
return reverse.toString();
}
split the string into an array of char, call sort, the build back up reversely into a string
String text = "Hi My name is Dave\n";
char arr [] = text.toCharArray();
Arrays.sort(arr);
for (int x = arr.length - 1; x >= 0; x--) {
System.out.print(arr[x]);
}
System.out.print("<end>");
output
yvsnmiieeaaMHD
<end>
new StringBuilder(text).reverse().toString()

How to eliminate Vowels from a string in java? [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
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!!

Use of array list and String comparison [closed]

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 8 years ago.
Improve this question
I need to read the names from a array list and compare them using loops and print the values from the array in the list
import java.io.*;
import java.util.*;
public class UniqueName {
public static void main(String args[]) throws IOException{
int wordcount = 0;
Scanner input = new Scanner(new FileReader("Names.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordcount ++;
}
}
}
System.out.println(wordcount);
}
}
Here is what you want:
import java.io.*;
import java.util.*;
public class UniqueName {
public static void main(String args[]) throws IOException{
Scanner input = new Scanner(new FileReader("Names.txt"));
Set<String> uniqueNames = new HashSet<String>();
while (input.hasNextLine()) {
String line = input.nextLine();
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordcount ++;
}
uniqueNames.add(str[i]);
}
}
System.out.println(wordcount);
System.out.println(uniqueNames);
}
}
Using a set, it only adds the value you pass if it doesn't already exist in it.
Then you can print it out with println(uniqueNames); which will print out each element like so: "[name1, name2, name3, ..., nameN]"
To get rid of the brackets and commas, you can use this:
String str = uniqueNames.toString();
str = str.replace('[', '');
str = str.replace(']', '');
str = str.replace(',', '');
If you want to get each one on a new line, you can change replace(',', '') to: replace(',', '\n');
here you go, try to learn something from it :)
public static void main(String args[]) throws IOException {
Scanner input = new Scanner(new FileReader("names.txt"));
// this is the arraylist to keep all the names from your file
ArrayList<String> names = new ArrayList<String>();
while (input.hasNextLine()) {
// since some of the names have spaces at the end, we pass them
// trough a cleanup method to remove the spaces
String line = clearSpaces(input.nextLine());
// add the cleaned up names to the arraylist
names.add(line);
}
// loop through all the names in the array for comparisson
for (int c = 0; c < names.size(); c++) {
// set each name to be unique until proven otherwise
boolean unique = true;
// take the name out of the array to test
String testString = names.get(c);
// loop through all the other names in the array for comparisson
for (int i = 0; i < names.size(); i++) {
// only if the indexes are different the comparisson makes sense
if (i != c) {
// take the name out of the array to test against
String tempString = names.get(i);
// test the names against each other
if (testString.equals(tempString)) {
// if they are the same then it's not unique
unique = false;
// break the loop cause we already know it's not unique
break;
}
}
}
// only if the unique boolean value is still true
// after testing against all other names
if (unique)
// print the name of that unique name
System.out.println(testString);
}
}
// returns a string clean of spaces
private static String clearSpaces(String withSpaces) {
// string builder for the string output
StringBuilder withoutSpaces = new StringBuilder();
char[] chars = withSpaces.toCharArray();
// loop the array of characters
for (char c : chars) {
// if it's not equal to 32 which corresponds to space char
if (c != 32) {
// append it to the string builder
withoutSpaces.append(c);
}
}
// return all the chars as string
return withoutSpaces.toString();
}

Categories