Split Strings, Search and Translate Substrings 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 6 years ago.
Improve this question
I'm pretty new to Java, and I need to solve this problem for an assignment. Can anyone help me please?
The problem is we need to enter a String like "AUGUUUUCU" and then split it into three letter strings like "AUG", "UUU", "UCU".
After that I would have to iterate over these and translate them to "AUG = METIONINA", "UUU = FENILANINA", "UCU = SERINA". Can anyone help me with this?
I already found a way to split them:
public class Main {
public static void main(String[] args) {
String str = "AUG-UUU-UCU";
String delimiter = "-";
String[] temp;
temp = str.split(delimiter);
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
}
}

If you're supposed to take user input, then you'll need to use a Scanner:
Scanner sc = new Scanner(System.in);
String input = sc.next();
To split it into three-letter Strings, use an array and store the substrings in the array using a for loop:
String[] subs = new String[input.length()/3];
int index;
for (int i=0; i<input.length(); i++) {
index = i*3;
subs[i] = input.substring(index, index+3);
}
You could then iterate over the array with another for loop and use a switch statement to determine the correct output:
for (int i=0; i<subs.length; i++) {
switch(subs[i]) {
case "AUG":
System.out.println("METIONINA");
break;
case "UUU":
System.out.println("FENILANINA");
break;
case "UCU":
System.out.println("SERINA");
break;
default:
break;
}
}
Note the break statements within the switch block. These are important to include; without break statements, it will simply execute all code after the matching case.

You could create an array that holds the values that are to be translated.
translateArray = new String[3];
Then you could set the values of the parallel array based on the input you receive. Then you could post those values.
for (int i=0; i<temp.length ; i++) {
if (temp[i] == "AUG" ) {
translateArray[i] = "METIONINA";
}
if (temp[i] == "UUU") {
translateArray[i] = "FENILANINA";
}
if (temp[i] == "UCU") {
translateArray[i] = "SERINA";
}
System.out.println(temp[i] + " = " + translateArray[i]);
}
Maybe that will work better for you.

To split a string into strings 3 chars long is 1 line:
String[] words = str.split("(?<=\\G...)");

Related

Replace non-digit characters from an array of String and return a String 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 6 months ago.
Improve this question
I need to replace non-digit characters from an array of String and return a String with digits separated by coma, actually, I made it but don't like it.
The first thing I made, was added values from the String array to the String.
Then I replaced non-digit characters from a String.
After that, I added digit values to an int array and sorted it.
Then I added all this stuff to an array of strings and separated values with commas, after that I returned it.
I would be glad for advice, thanks for attention.
import java.util.Arrays;
class Test {
private static String sortedStringOfNumber(String[] string) {
StringBuilder temp = new StringBuilder();
for (String s: string) {
temp.append(s);
}
String numberOnly = temp.toString().replaceAll("[^0-9]", "");
int[] numbers = new int[numberOnly.length()];
for (int i = 0; i < numberOnly.length(); i++) {
numbers[i] = numberOnly.charAt(i) - '0';
}
Arrays.sort(numbers);
String[] result = new String[numbers.length];
for (int i = 0; i < numbers.length; i++) {
result[i] = String.valueOf(numbers[i]);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++) {
sb.append(result[i].toString());
if (i != result.length - 1)
sb.append(", ");
}
return sb.toString();
}
public static void main(String[] args) {
String[] arrayStringData = new String[] { "1", "ab3c", "level", null, "java2s.com", "asdf 456", "Br0C0de" };
//Should be "0, 0, 1, 2, 3, 4, 5, 6"
System.out.println("Sorted string of numbers ->\t" + sortedStringOfNumber(arrayStringData));
}
}
Your solution would run in O(n*log n) mainly due to Arrays.sort.
Use a simple counting sort. This would give you a runtime of O(n).
Look at the string and ignore all other non-digits.
You might also try it this way:
String sortedIntsCsv = Arrays.stream(string).map(s -> s.replaceAll("\\D", "")).mapToInt(Integer::valueOf).sorted().mapToObj(String::valueOf).collect(Collectors.joining(","));

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

How to reverse word leaving all instance of q in place [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 7 years ago.
Improve this question
How do I write a method that will reverse the letters of each word in a string while leaving all instances of ‘Q’ or ‘q’ in place (stay at the current index). Each word is separated by whitespace(‘ ‘).
Examples:
Hello Worldq > olleH dlroWq
Hiq BQb -> iHq bQB
kjnoqKl -> lKonqjk
jkQuq -> ukQjq
public String reverseWords(String s) {
String[] sub = s.trim.split(“q + ”);
String result = ””;
if (sub.length > 0) {
for (int i = sub.length - 1; i > 0; i--) {
result += sub[i] + ““;
}
}
return result;
}
Here is my solution. What I did first was parse the initial String so we can get individual words. From there, I replaced all the Q and q for that word with an empty string and then reversed it using StringBuilder. Well with StringBuilder you can also insert pretty easily, so I looped back through the word and added all the Q and q back to the orginial spot.
public static void main(String... array){
System.out.println(reverseWords("Hello Worldq"));
}
public static String reverseWords(String s) {
String[] words = s.split(" ");
StringBuilder output = new StringBuilder(words.length);
for (String word : words){ //Iterate through words
StringBuilder temp = new StringBuilder(word.replaceAll("[Qq]", "")).reverse(); //Replace Q's and reverse
for (int i =0; i<word.length(); i++){ //find Q's
char tempChar = s.charAt(i);
if (tempChar == 'Q'){ //If q found insert
temp.insert(i, "Q");
}
if (tempChar == 'q'){
temp.insert(i, "q");
}
}
output.append(temp); //Add to final output
output.append(" "); //Do not forget about space
}
return output.toString();
}
Hope this helps!
Edit:
Some after thoughts, you could potentially store the indexes of the Q's when iterating through the word initially when trying to replaceAll. That way you replaceAll and have the indexes of all the Q's with one iteration instead of 2.
I would do it in two step. First of all, construct a list, or array containing all letters that are not Q or q. Reverse the array.
Then you reconstruct the array by replacing all the non q letters with the reveresed array like this:
int reversedIndex = 0;
for(int i=0; i<s.length(); i++){
if (s.charAt(i) != 'q' && s.charAt(i) != 'Q') {
s[i] = reversedArray[reversedIndex];
reversedIndex++;
}
}
I leave you to make the code to program the reversedArray
Why not just implement a spare string/array with the q or Q included, reverse the string/array to the place -1 space for the q or Q, and if you come across one in your word/place in the array just do nothing be an if statement in your reverse method.Then put that in an string/array. Take the next part of the string/array and do the same until your original word is empty, return the final string/array, whatever you want to use, and done

How can i read 1,A,5,B with scanner and put it while reading in a string and an int vector in Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
So, i have this input at once:
1,A,5,B,10,A,8,A,17,B,17
I have these 2 lists:
String[] bidderName = new String[100];
int[] bidValue = new int[100];
I want, as i read this at once, to be able to store the numbers(1,5,10 etc.) in the bidValue list, and the names(A,B, etc.) in the biddername list.
How can i do this using java.util.Scanner, or anything else?
Than you in advance. Respects!
I assume that the letters are the bidder names,
and that your input starts with a bidder name.
public class Test055 {
public static void main(String[] args) {
String input = "A,5,B,10,A,8,A,17,B,17,B,1";
String[] bidderName = new String[100];
int[] bidValue = new int[100];
String[] data = input.trim().split(",");
int k = 0;
for (int i = 0; i < data.length; i += 2) {
bidderName[i/2] = data[i];
bidValue[i/2] = Integer.parseInt(data[i + 1]);
k++;
}
for (int i = 0; i < k; i++) {
System.out.println(bidderName[i] + " // " + bidValue[i]);
}
}
}
You could use a Scanner, but I wouldn't. The input is short enough (unless you have thousands of these) to read it in once and use Java regular expressions:
String s = "1,A,5,B,10,A,8,A,17,B,17";
String[] split = s.split(",");
for (String current : split) {
if (current.matches("^\\d+$")) {
System.out.println("handle number " + current);
} else
System.out.println("handle letter " + current);
}
Consider using an ArrayList rather than an array so you don't have to know the number of elements in each "array" up front.
First try to do it by yourself
Split the string using ',' use split(",") then you will get string array which contains both letters and numbers
if you are sure that sequence follows same pattern add every odd index tokens to int array using Integer.parseInt()
put even indexes directly to your array
You don't specify where the input is coming from, but for example, if it's coming from System.in, you could do something like this:
String[] bidderName = new String[100];
int[] bidValue = new int[100];
int bvIndex = 0;
int bnIndex = 0;
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
bidderValue[bvIndex++] = scanner.nextInt();
else {
bidderName[bnIndex++] = scanner.next();
}
}
You would want some sort of terminal condition in addition to scanner.hasNext(), but that's up to you to determine.

Algorithm:Find first non-repeated character in an input string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have seen this and this question but mine is different. I want to write an efficient code for it in java. I came up with 2 solutions:
Approach 1.
find_first_reapeted(char[] input)
{
HashMap<Character,Integer> myhash = new HashMap<Character,Integer> ();
for(int i=0;i<input.length;i++)
{
if(myhash.containsKey(input[i])
myhash.put(input[i],2); //just put 2 even if it is more than 2
else
myhash.put(input[i],1);
}
for(int i=0;i<input.length;i++)
{
if(myhash.getValue(input[i])==1)
return input[i];
}
}
Approach 2.
find_first_reapeted(char[] input)
{
int[] allchars = new int[26];
for(int i=0;i<input.length;i++)
{
allchars[input[i]-'a'] += 1;
}
for(int i=0;i<input.length;i++)
{
if(allchars[input[i]-'a']==1)
return input[i];
}
}
First is there any better solution? (int term of time and space complexity)?
If not which one of the the above is better? I'm not sure about the space complexity of hashmap!
How about
The first repeating character.
char find_first_repeated(char[] input) {
BitSet bs = new BitSet();
for(char c : input) {
if(bs.get(c))
return c;
bs.set(c);
}
return '\uffff'; // invalid char
}
The first non repeating character, I would use the second approach but using the for-each loop to make it cleaner.

Categories