How to get the common first substrings In two Strings - java

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();
}

Related

How do I break a string into groups of letters with a loop in Java?

I have to write a method which breaks a string into groups. The user should give the amount of letters per group and the function should return a string that consists of the input string broken into groups. For instance, function(“HELLOYOU”, 2) would return “HE LL OY OU”.
You can use String.split() to break the string into an array of individual letters, and then combine pairs of letters, or larger groups, etc.
Here is some example code:
String[] splitInParts(String input, int size) {
String[] letters = input.split("");
String[] output = new String[letters / size];
for (int i = 0; i < output.length; i++) {
output[i] = "";
for (int j = 0; j < size; j++) {
output[i] = output[i] + letters[size * i + j];
}
}
return output;
}
There is a lot of boilerplate code missing, for example, checking that loop parameters are in range, checking strings are not null, etc. However this is a rough idea of how you could go about doing it.
You can move the characters of input String to a new String and put whitespaces on every step that equals to "size":
String function(String input, int parts) {
StringBuilder result = new StringBuilder();
int partCounter = 0;
for (int i = 0; i < input.length(); i++) {
partCounter++;
result.append(input.charAt(i));
if (partCounter == parts){
result.append(" ");
partCounter = 0;
}
}
return result.toString();
}
You could use the below code that takes in a String instance and aN int defining the number of characters to split based on. And then use the String instances split method.
public static String[] split(String input, int len){
// To prevent any NullPointerException being thrown
if (StringUtils.isEmpty()) {
return null;
}
// Split the input string based on a regex pattern
return input.split(String.format("(?<=\\G.{%1$d})", len));
}
The Regular Expression that is being used here is (?<=\\G.{%1$d}) which based on len being 2 would become (?<=\\G.{2}). So this means it would split every 2 characters. So the output for a string of HELLOWORLD would be HE, LL, OW, OR, LD .
If you wanted to join those into one String separated by a space you could using the StringUtils#join method.
String joinedString = StringUtils.join(split, StringUtils.SPACE);
Which would produce "HE LL OW OR LD".
So an all in one method would be:
public static String separateNthCharacter(String input, int len) {
// To prevent any NullPointerException being thrown
if (StringUtils.isEmpty()) {
return StringUtils.EMPTY;
}
String[] split = input.split(String.format("(?<=\\G.{%1$d})", len));
return StringUtils.join(split, StringUtils.SPACE);
}

manipulating the strings to make new strings with the respective indexes

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.

String length() comparison is not working properly

public class LongWord {
public static void main(String args[]) {
String text = "my brother is taller than me#1233334. I always a short man,but smart than him";
// Find the longest word in the String
String[] words = text.split("\\s");
String longestWord = "";
for (int i = 1; i < words.length; i++) {
int firstLen = words[i - 1].length();
int secondLen = words[i].length();
if (firstLen <= secondLen) {
longestWord = words[i];
}
}
System.out
.println("===================================================\nLongest Word:::: \n");
System.out.println(longestWord);
}
}
// This is the sample program to find the longest word in the statement. so the output should be "me#1233334" word. but I am getting "man,but" word as output. can anyone please help me what is wrong with program.
Your method doesn't find the largest string in an array of strings. It finds the last string in an array of strings which is larger than the string directly before it.
Your comparison (firstLen <= secondLen) doesn't compare either of the strings to the current longest string. Your main loop should be:
String longestWord = words[0];
for(String word : words) {
if(word.length() > longestWord.length()){
longestWord = word;
}
}
You can also use for(int i = 0; i < words.length(); i++) and use words[i] instead of (String word : words) and word
The logic for deciding the longest word is wrong.
You are comparing a "word" (in this context, word just means something separated by a white space) with the previous word, and if it is longer, that is now the longest.
man,but is selected because it is simply longer than its previous word (short). Note that nothing after man,but is selected because no words after that are longer than their previous word
You're doing it wrong. You aren't comparing if the secondLen is bigger than longestWord, it should actually be:
longestWord = words[0];
for (int i = 1; i < words.length; i++) {
int longestLen = longestWord.length();
int secondLen = words[i].length();
if (longestLen <= secondLen) {
longestWord = words[i];
}
}

Reversing A String. Every other word reversing

So i've got a for loop that's reversing every other word in a string. I can't determine which condition is causing this.
for (int i = 0; i < words.length; i++)
{
stringBuilder.append(words[(words.length-1)-i]);
stringBuilder.reverse()
}
newMessage = stringBuilder.toString();
return Message
stringBuilder.reverse() reverse the whole string that you are currently building at each iteration.
Try:
for (int i = 0 ; i < words.length ; i++) {
String word = words[(words.length-1)-i];
String reverse = new StringBuilder(word).reverse().toString();
stringBuilder.append(reverse).append(" ");
}
Or even simpler, reversing at the end:
for (int i = 0 ; i < words.length ; i++) {
stringBuilder.append(words[(words.length-1)-i]).append(" ");
}
newMessage = stringBuilder.reverse().toString();
Edit based on comments:
for (String w : words) {
String reverse = new StringBuilder(w).reverse().toString();
stringBuilder.append(reverse).append(" ");
}
newMessage = stringBuilder.toString();
stringBuilder.reverse(); is reversing the whole word comment that line and your code wont reverse your new message
var string = "hello world";
function reverseWords(string) {
var words = string.split(' '),
finals = [];
words.forEach(function(word) {
finals.push(word.split('').reverse().join(''););
});
return finals.join(' ');
}
reverseWords(string); // "olleh dlrow"
First of all, your loop is more complex then it needs to be. If you want to reverse words starting from the end, you should just use the loop index to do that, you don't need the (words.length-1)-i calculation.
Another thing, when you call reverse() on a StringBuilder you are reversing the whole string not just the appended portion. What you can do is use a temp StringBuilder to perform the reversal and a temp String variable to separate reversal from appending.
Something like this:
StringBuilder reversedBuilder = new StringBuilder();
for (int i = words.length - 1; i >= 0; i --)
{
String reversed = reversedBuilder.append(words[i]).reverse().toString(); // reverse the word
stringBuilder.append(reversed).append(" ");
reversedBuilder.setLength(0); // clear the reversed
}
If you want, you can do this in a single line of code (added with comments for clarification):
for (int i = words.length - 1; i >= 0; i --)
{
stringBuilder.append(new StringBuilder() // create a temp string builder
.append(words[i]) // add the current word to temp string builder
.reverse() // reverse the current word in the temp string builder
.toString()) // add the reversed word to stringBuilder
.append(" "); // add the space to stringBuilder
}

Finding characters in a string

i'm doing an encoding program where i'm supposed to delete every character in the string which appears twice. i've tried to traverse through the string but it hasn't worked. does anyone know how to do this? Thanks.
public static String encodeScrambledAlphabet(String str)
{
String newword = str;
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
newword += alphabet;
newword = newword.toUpperCase();
for (int i = 0, j = newword.length(); i < newword.length() && j >=0; i++,j--)
{
char one = newword.charAt(i);
char two = newword.charAt(j);
if (one == two)
{
newword = newword.replace(one, ' ');
}
}
newword = newword.replaceAll(" ", "");
return newword;
}
Assuming that you would like to keep only the first occurrence of the character, you can do this:
boolean seen[65536];
StringBuilder res = new StringBuilder();
str = str.toUpperCase();
for (char c : str.toCharArray()) {
if (!seen[c]) res.append(c);
seen[c] = true;
}
return res.toString();
The seen array contains flags, one per character, indicating that we've seen this character already. If your characters are all ASCII, you can shrink the seen array to 128.
Assuming by saying deleting characters that appears twice, you mean AAABB becomes AAA, below code should work for you.
static String removeDuplicate(String s) {
StringBuilder newString = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
String s1 = s.substring(i, i + 1);
// We need deep copy of original String.
String s2 = new String(s);
// Difference in size in two Strings gives you the number of
// occurences of that character.
if(s.length() - s2.replaceAll(s1, "").length() != 2)
newString.append(s1);
}
return newString.toString();
}
Efficiency of this code is arguable :) It might be better approach to count the number of occurences of character by a loop.
So, from the code that you've shown, it looks like you aren't comparing every character in the string. You are comparing the first and last, then the second and next to last. Example:
Here's your string:
THISISTHESTRINGSTRINGABCDEFGHIJKLMNOPQRSTUVWXYZ
First iteration, you will be comparing the T at the beginning, and the Z at the end.
Second iteration, you will be comparing the H and the Y.
Third: I and X
etc.
So the T a the beginning never gets compared to the rest of the characters.
I think a better way to do this would be to to do a double for loop:
int length = newword.length(); // This way the number of iterations doesn't change
for(i = 0; i < length; i++){
for(j = 0; j < length; j++){
if(i!=j){
if(newword.charAt(i) == newword.charAt(j)){
newword.replace(newword.charAt(i), ' ');
}
}
}
}
I'm sure that's not the most efficient algorithm for it, but it should get it done.
EDIT: Added an if statement in the middle, to handle i==j case.
EDIT AGAIN: Here's an almost identical post: function to remove duplicate characters in a string

Categories