Compare two Strings letter by letter - java

Well, I have two strings to compare and check letter by letter if they match, and if hits a '-' i need to count how many '-' there's in sequence and put them in a group as if they were only one char and count how many T and C there in this group of '-'. The output should be like 2.1T and 2.2C and the other one 5.2C.
String dna1 = "TC---CA--";
String dna2 = "TCTCCCACC";
char[] dnaChar = dna1.toCharArray(), dna2Char = dna2.toCharArray();
int cont = 0;
int letters = 0;
for (int i = 0; i < dnaChar.length; i++) {
if (dnaChar[i] != dna2Char[i]) {
int mut = i + 1;
if (dna1.charAt(i) == '-') {
cont++;
mut -= cont;
if (dna2.charAt(i) == 'C') {
letters++;
}
System.out.println(mut + "." + letters + dna2.charAt(i));
} else {
letters = 0;
cont = 0;
mut += 1;
System.out.println("" + dna1.charAt(i) + " " + mut + " " + dna2.charAt(i));
}
}
}
The output
2.0T
2.1C
2.2C
4.3C
4.4C
And what i want 2.1T 2.2C 5.2C

The output that you expect will never be obtained from your above code.. Because in your if construct will be executed every time you encounter a '-' in your first string.. And hence you will have 5 outputs, not 3..
Second, to get what you need, you will have to do some extra work here..
First When you encounter a '-' in your 1st String, you need to store the corresponding character from your second String into some variable.. Because you need it to check for continuous characters.
Second, each time to get a '-', check the current character with the last character matched for the previous '-'. If it is the same, increase the count by 1,
If it is not the same, just print what you want.. and reset your count to 0
As soon as you encounter the character which not '-' in your first string, print the current character and the count value, and reset them..
You can try to code according to the steps I have mentioned..
*PS: - For any problem you get to code, you should first write down the steps you should follow to solve it on paper. Then convert it to code step-by-step. It will be easier to understand the problem and solve it also..

Related

Calculate occurrence of given letter in sentence in Java [duplicate]

This question already has answers here:
Simple way to count character occurrences in a string [duplicate]
(15 answers)
Closed 4 years ago.
String sentence = JOptionPane.showInputDialog (null, "Write a sentence.");
String letter = JOptionPane.showInputDialog(null, "Write a letter");
while (true) {
if (letter.equals("Stop"))
System.exit(0);
//to calculate number of specific character
else {
int countLetter = 0;
int L = letter.length();
for (int i = 0; i < L; i++) {
if ((letter.charAt(i) = .....))
countLetter++;
}
}
}
Is it possible to replace the dots to make the program count how many times the given letter occures in the sentence written in the first string?
Since Java 8, there is an elegant solution to this.
int count = letter.chars().filter(ch -> ch == 'e').count();
This will return the number of occurences of letter 'e'.
if your String letter contains a one character use this letter.charAt(0) and then replace dots with this. Also remember to use == instead of = here. = means you are just asigning and == uses to compare two values.
If you have to use a for loop and want to stick to the old fashioned way, try this:
String sentence = "This is a really basic sentence, just for example purpose.";
char letter = 'a';
int occurrenceOfChar = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == letter) {
occurrenceOfChar++;
}
}
System.out.println("The letter '" + letter
+ "' occurs " + occurrenceOfChar
+ " times in the sentence \""
+ sentence + "\"");
The sentence and the letter are just examples, you have to read the user input.
You can use Guava Lib to perform this operation faster without iterating string.
CharMatcher.is('e').countIn("Write a letter");
Will return 3

Split a string in java according to characters with even or odd order

You input a word which is a string. What I want to do is to put the letters in an odd position in a variable and those on an even position in another variable...
But I have been reading online and all I can find is how to split by a specific character like: "/", "-" or "". But I dont have one.. show what should I use...
Should I solve this in an other way....
EX:
String S = "alfabet";
and I want to print out:
odd = "afbl";
even = "lae";
System.out.println(odd + " " + even);
I used two strings called odd and even and set both of them to be empty then i iterate throught all the letters of the string s and add the even characters to even and odd characters to odd like the following:
String S = "alfabet";
String odd="";String even="";
for(int c=0;c<S.length();c++)
{
if(c%2==0)odd+=S.charAt(c);
else even+=S.charAt(c);
}
Please do the following:
int i = 0;
StringBuilder oddString = new StringBuilder();
StringBuilder evenString = new StringBuilder();
while(i++ < S.length())
{
if(i & 1){
oddString.append(S.charAt(i));
}else{
evenString.append(S.charAt(i));
}
}
System.out.println("Even String: " + evenString);
System.out.println("Odd String: " + oddString);

I have to make a tweet tester in java, but can't figure out how to count the amount of times a character shows up in the tweet

Alright, so for a class I am taking I have to make a program that tests tweets. It asks you to input a tweet, then tells you if the tweet is valid (less than 140 characters), tells you the amount of mentions (indicated by the character #) and the number of hashtags (indicated by a #), and tells you whether or not it is a retweet (if it contains "RT:" it is considered a retweet).
I can tell whether it is a valid tweet and can tell if it is a retweet (I coded it so that if the index of "RT:" is greater than or equal to 0, it says it is a retweet), but can't figure out how to count the number of # and # in the string the user enters. I know how to find the index, but am having trouble finding out where to go from there. I don't know what to do as a next course of action. Is there a way to count the amount of a certain character in a string?
I know what the code is currently doing, outputting the index of the first time the character shows up, but I am lost on what else I could do. I thought that maybe I could truncate every letter before and including the # and use a loop to count the amount of times that I get an index for #, then do the same for the #, but I don't know how to truncate every letter before and including a certain character. Or is there a better option? Any help is appreciated
import java.util.Scanner;
import java.lang.Math;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet:");
String s = scan.nextLine();
int length = s.length();
if(length > 140)
System.out.println("Excess Characters: " + ( length - 140));
else{
System.out.println("Length Correct");
int at = s.indexOf('#');
System.out.println("Number of Mentions: " + (at));
int hash = s.indexOf('#');
System.out.println("Number of Hashtags: " + (hash));
if (s.indexOf("RT:") >=0)
System.out.println("The input was a retweet.");
else
System.out.println("The input was not a retweet.");
}}}
.indexOf will return the index of that character in your String.
That might not be the best approach to resolve your problem.
You could do something like this :
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) == '#') {
count++; //or whatever mechanism you want to keep track of those chars.
}
}
Improving slightly on Caleb's answer:
Since you know which two characters you need to count, '#' and '#,' you can have a counter for each and just iterate over the tweet once. Then you just check if a character is one you're looking for, and if it is, the counter is incremented!
int mentions = 0;
int hashtags = 0;
for(int i = 0; i < s.length; i++) {
if(s.charAt(i) == '#') {
mentions++;
} else if(s.charAt(i) == '#') {
hashtags++;
}
}
Now mentions and hashtags should have the countes of #'s and #'s respectively.
You can solve this problem by implementing a simple counting method:
public int charCount(char c, String tweet) {
int count = 0;
for(int i = 0; i < tweet.length()) {
if(tweet.charAt(i) == c) count++;
}
return count;
}
With this, you can count the number of times a character appears in a tweet.
System.out.println("Length Correct");
int at = charCount('#', s);
System.out.println("Number of Mentions: " + at);
int hash = charCount('#', s);
System.out.println("Number of Hashtags: " + hash);
if (s.indexOf("RT:") >= 0)
System.out.println("The input was a retweet.");
else
System.out.println("The input was not a retweet.");

Making a list of all combinations of 2 letters and 4 numbers

I have been trying to create a code that can make a list of all combinations of 2 letters and 4 numbers
EX: aa1111, ab1111
the only thing that i can come up with are programs that print combinations that are against my outline
EX: aatc9e, gj3ru7
What can I do that makes it so it stops at two letters and goes to the four numbers?
I'd do it as 3 while loops, and add each one.
It's also useful that Characters can be both letters and numbers.
Given you haven't added any code, here's some dirty pseudo code:
Output = New Array[]
char characterOne = 'A'
while characterOne < 26:
char characterTwo = 'A'
while characterTwo <26:
char Number = '0000'
while Number < 9999:
Output.add (CharacterOne + CharacterTwo + Number.toString)
Number ++
characterTwo++
characterOne++
Remember; stack overflow likes specificity, include your code next time.
This process is rather involved as you are going to generate combinations of strings from
aa0000 - zz9999.
It can be done with one while loop, an Array of two Strings, and one int. You'll have to know when your number > 9999 so you can increment the second letter (letters[1]), then you have to know when the second letter is about to pass "z" so you can increment the first letter (letters[0]) and start the second letter back at "a".
public static void main(String[] args) throws Exception {
String alphabet = "abcdefghijklmnopqrstuvwxyz";
String[] letters = new String[] { "a", "a" };
int number = 0;
String combination = letters[0] + letters[1] + String.format("%04d", number);
while (!combination.contentEquals("zz9999")) {
// Output the combination
System.out.println(combination);
number++;
if (number > 9999) {
int letterIndex = alphabet.indexOf(letters[1]) + 1;
if (letterIndex < alphabet.length()) {
// Get the next letter in the alphabet
letters[1] = String.valueOf(alphabet.charAt(letterIndex));
} else {
// We've passed z, so we need to increment the first letter
letterIndex = alphabet.indexOf(letters[0]) + 1;
if (letterIndex < alphabet.length()) {
// Get the next letter in the alphabet
letters[0] = String.valueOf(alphabet.charAt(letterIndex));
}
// Start back at letter a
letters[1] = "a";
}
// Start back at zero
number = 0;
}
// Format the next combination
combination = letters[0] + letters[1] + String.format("%04d", number);
}
// Print the last combination
System.out.println(combination);
}
Seeing that this is your first question on SO, next time post code that shows an actual attempt to your question. Don't just post a question without giving an effort to solve it yourself, and expect SO to solve it for you.

Not able to understand string permutation Java code

I have this working code to print string permutations without repetitions, but not able to wrap my head around how is it working as in logic. Any suggestions will be really helpful.
private static void permutation(String input, String sofar) {
if (input.equals("")) {
System.out.println(count + " " + sofar);
count++;
}
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (input.indexOf(c, i + 1) != -1)
continue;
permutation(input.substring(0, i) + input.substring(i + 1), sofar+c);
}
}
Function call:
String input = "ABBCD";
permutation(input, "");
for (int i = 0; i < input.length(); i++) {
The above for loop is doing the magic
Input ABCD
Iterations
input: BCD sofar: A .... recursion goes on
input: ACD sofar: B ....
input: ABD sofar: C ....
input: ABC sofar: D .....
Hope this helps
Just remember that recursion is usually a stop condition, and an attempt to solve a smaller problem using the recursive call, under the assumption that the recursion works.
I've commented the code so you can replace that with your copy to keep track of what it's doing when you get back to it. Add your own comments once you understand as they'll help you follow what happens:
Part 1: The basic condition / stop condition:
if (input.equals("")) {
System.out.println(count + " " + sofar);
count++;
}
This part stops the recursion and returns a result, the base case being an empty string, which has a single permutation that is also an empty string.
Part 2: Iterating smaller problems.
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
// ...
permutation(input.substring(0, i) + input.substring(i + 1), sofar+c);
}
This part uses the recursive call on a smaller (by one character) string, to solve the problem. It calls the same string omitting a character it prepends to whatever following results it generates. We know the call generates all permutations (that's our assumption). So we now know what the recursion does.
Part 2.1: The de-duplicating "if":
This is probably the trickiest part here...
if (input.indexOf(c, i + 1) != -1)
continue;
Let's figure this out. What it means, is: "try and find a character the same as the one selected, and if one exists, skip this iteration and it's generated solutions".
Think of a word like "ABBA" it will skip the first "A" and "B", but not the last ones. Why? Well, since order of similar characters does not matter (if we tag the character A1 B1 B2 A2, and now replace them: A2 B2 B1 A1, this is still the same word, so there is only one permutation for words like "AA", since A1 A2 is the same as A2 A1.
Taking the last characters is easier, since we don't need to maintain a list of the characters we already used in this iteration.
The full code with basic comments:
private static void permutation(String input, String sofar) {
if (input.equals("")) {
// this is the stop condition
// the only permutation of "" is ""
System.out.println(count + " " + sofar);
// this counts how many permutations were outputted.
count++;
}
for (int i = 0; i < input.length(); i++) {
// this loop basically means "take every
// possible character, and append permutations of all
// other characters to it.
char c = input.charAt(i);
if (input.indexOf(c, i + 1) != -1)
// this makes sure we only take a single "A" or "B"
// character in words like "ABBA", since selecting
// the same character would create duplicates
continue;
// this creates a new string without the selected character
// and under the assumption the recursion works
// appends all permutations of all other characters
// to it
permutation(input.substring(0, i) + input.substring(i + 1), sofar+c);
}
}
if (input.equals("")) {
System.out.println(count + " " + sofar);
count++;
}
This step is passed as the input is not "". Note that you could simply use input.empty() here. The only thing to remember here is that count have not been incremented.
for (int i = 0; i < input.length(); i++) {
This will, loop over all character of the input
char c = input.charAt(i);
if (input.indexOf(c, i + 1) != -1)
This check if the next character is equal to the current one, if it does then it will jump directly to the next iteration(the next character) using the continue keyword.
If it does not, then it will recall the method (We call that recursivity), passing in the string without the current char. But giving it back to sofar.
permutation(input.substring(0, i) + input.substring(i + 1), sofar+c);
Now in the case where input is empty,
The count of non-distinct character will be printed + all these character.

Categories

Resources