After testing my code, I found a bug which I don't know how to fix.
When I start this code with String parameter = "asd fgh", then I see this output "hgf" instead of "hgf dsa".
public String reverseWords(String input) {
String oneOrMoreSpaces = "\\s+";
String[] words = input.split(oneOrMoreSpaces);
String completeAnagram = "";
for (int i = 0; i < words.length; i++) {
char[] symbol = words[i].toCharArray();
char newSymbolSequence;
int j = symbol.length - 1, k = 0;
while (k < j) {
if (!Character.isAlphabetic(symbol[k]))
k++;
else if (!Character.isAlphabetic(symbol[j]))
j--;
else {
newSymbolSequence = symbol[k];
symbol[k] = symbol[j];
symbol[j] = newSymbolSequence;
k++;
j--;
}
}
completeAnagram = new String(symbol);
}
return completeAnagram;
}
I see that you split the input , if it contains spaces by
String[] words = input.split(oneOrMoreSpaces);
then you cycle through them with a for loop .
each word words is stored in char[] symbol = words[i].toCharArray();
the problem is completeAnagram = new String(symbol);
when you run the loop out of every words , it stores only the recent ran one ; hence , when you run the last loop , it holds only the last word which is analyzed .
Related
input :have anic eday
String[] words = sb.toString().split("//s");
StringBuilder sbFinal = new StringBuilder();
for(int i=0;i<words[0].length() ;i++){
for(int j=0;j<words.length;j++){
sbFinal.append(words[j].charAt(i));
}
}
return sbFinal.toString() ;
output : have anic eday
I have a number of strings which I need to convert in the form where a new set of strings are printed ( space seperated ) which are formed by the respective chars of each strings given .
desired output : hae and via ecy
for example we have 3 words of 4 chars each , we want 4 words of 3 chars each .
have anic eday =>hae and via ecy
we pick 1st char from all 3 words to make the new first word .
I used the code shown above but it prints the input as output itself .
Use simple for loops and an array:
public class SO {
public static void main(String args[]) {
String input = "have anic eday ";
// Split the input.
String[] words = input.split("\\s");
int numberOfWords = words.length;
int wordLength = words[0].length();
// Prepare the result;
String[] result = new String[wordLength];
// Loop over the new words.
for (int i = 0; i < wordLength; i++) {
// Loop over the characters in each new word.
for (int j = 0; j < numberOfWords; j++) {
// Initialize the new word, if necessary.
String word = result[i] != null ? result[i] : "";
// Append the next character to the new word.
String newChar = Character.toString(words[j].charAt(i));
result[i] = word + newChar;
}
}
for (String newWord : result) {
System.out.println(newWord);
}
}
}
Output:
hae
and
via
ecy
Although answered, I made up a more similar version to what you have originally designed, just with sysout instead of return, but change to your needs, or just adjust the .split() line:
String sb = "have anic eday";
String[] words = sb.split("\\s"); //you need to use BACKWARDSLASH "\\s" to get it to work.
StringBuilder sbFinal = new StringBuilder();
for (int i = 0; i < words[0].length(); i++) {
for (int j = 0; j < words.length; j++) {
sbFinal.append(words[j].charAt(i));
}
sbFinal.append(" ");
}
System.out.println(sbFinal.toString());
You split with "//s", however " " or "\\s" seems to work perfectly fine.
I need some help, I have two Strings and I want to get the first occurrence of common substrings.
1st String : abacdefghi
2nd String : abaciopiss
I want to get the substring
substring : abac
Thank you everyone.
It maybe isn't the best solution but my attempt would be to find the first matching characters in each string and then continue to check the following characters if they are still the same:
private static String extractFirstEqual(String a, String b) {
//Split your string into an array of characters
String[] arr = a.split("");
String[] brr = b.split("");
StringBuilder result = new StringBuilder();
//Iterate over both arrays
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < brr.length; j++) {
//Find first matching character
if (arr[i].equals( brr[j])) {
//While there are more characters in both arrays and the characters keep matching, append them
// to the result
while (arr[i].equals(brr[j]) && i < arr.length && j < brr.length) {
result.append(arr[i]);
i++;
j++;
}
return result.toString();
}
}
}
return result.toString();
}
I'm having trouble understanding why the string I'm trying to build out of this for-loop is only returning one character. I have a 4 character string that I iterate through for all the chars that match '0', but the logic only occurs once throughout. What am I missing?
private void updateDurationColor(SpinClassMovement movement){
String duration = (String) TextFormatUtil.getFormattedTimeInMinutesAndSeconds(movement.getMovementLengthInMinutes() + movement.getMovementLengthInSeconds());
for(int i = 0; i < duration.length(); i++){
if (duration.charAt(i) == '0'){
Character zero = duration.charAt(i);
StringBuilder colorDuration = new StringBuilder(zero);
colorDuration.append(zero);
setColor(mTimeRemaining,duration,colorDuration,Color.GRAY);
}
}
}
I think it's because your are initializing "colorDuration" inside the loop. Try this.
private void updateDurationColor(SpinClassMovement movement){
String duration = (String) TextFormatUtil.getFormattedTimeInMinutesAndSeconds(movement.getMovementLengthInMinutes() + movement.getMovementLengthInSeconds());
StringBuilder colorDuration = new StringBuilder();
for(int i = 0; i < duration.length(); i++){
if (duration.charAt(i) == '0'){
Character zero = duration.charAt(i);
colorDuration.append(zero);
setColor(mTimeRemaining,duration,colorDuration,Color.GRAY);
}
}
}
I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}
Say I have a string, and I want to change the second "a" in that string to an "e".
String elephant = "elaphant";
I tried using String.replace(), but that replaces all the a's in the string, returning "elephent".
elephant.replace("a", "e");
Is there any loop or method I can use to accomplish this? Thank you all.
You could convert it to a char array, switch out the desired letter, then convert it back to String?
String elephant = "elaphant";
int index = -1;
int count = 0;
while(count < 2) {
index = elephant.indexOf("a", index+1);
count++;
}
if(index >= 0 && index < elephant.length()) {
char[] tmp = elephant.toCharArray();
tmp[index] = "e";
elephant = new String(tmp);
}
Or if you prefer StringBuilder
StringBuilder sbTemp = new StringBuilder(elephant);
sbTmp = sbTmp.replace(index, index+1, "e");
elephant = sbTmp.toString();
You need to get the index of the first occurrence of a letter.
Try using the indexOf method.
int myIndex = elephant.indexOf('a');
Once you have the index, use StringBuilder to replace the value. Something like:
StringBuilder sb = new StringBuilder(elephant);
sb[index] = myIndex;
elephant = sb.ToString();
Code:
String elephant = "elaphant";
//convert the string to array of string
String[] sp = elephant.split("");
int countA = 0;
boolean seenTwice = false;
String result = "";
for (int i = 0; i < sp.length; i++) {
//count number of times that a has been seen
if (sp[i].equals("a")) {
countA++;
}
// if a has been seen twice and flag seenTwice has not been see
if (countA == 2 && !seenTwice) {
result += "e";
seenTwice = true;
} else {
result += sp[i];
}
}
System.out.println(result);
Output:
elaphent