Sequence in groups of 10 characters - java

I am working on this assignment and I wanted to know how can I display sequence in groups of 10 characters at a time.
Below is the working program screenshot:
I want to group 10 characters in the output box, for example:
1 CTCTAACGCG CAAGCGCATA TCCTTCTAGG
61 ....
There are about 60 characters in each line excluding spaces and the number, so there must be 6 groups of 10 characters.
Below is the code I made to display this output:
public void dispLines() {
// Get the selected value of characters per line and assign it to noc variable
String noc = numOfChar.getSelectedItem().toString();
// Call StringBuffer object and assign sb variable to it
StringBuffer sb = new StringBuffer();
// Assign raw dna data to dna variable, where string will be mutated
String dna = rawDNAInput.getText();
// Create newdna variable to store the newly created data
String newdna = "";
// Loop through the size of raw dna
for (int i = 0 ; i < dna.length (); ++i)
{
// Assign every single character to StringBuffer sb
sb.append(dna.charAt (i));
}
// Assign the StringBuffer sb values to the newdna variable
newdna = sb.toString();
// Recall StringBuffer object, so new data can be assigned
sb = new StringBuffer();
// Assign start varaible of 0
int start = 0;
// Assign end varaible to be start + number of characters per line
int end = start + Integer.parseInt(noc);
// Keep looping till end value is less than the length of the dna
while(end < newdna.length())
{
// Append values into StringBuffer sb varaible by calling makeNumberedStr method
sb.append(makeNumberedStr(newdna.substring(start, end), start + 1));
// Increment start variable by the selected numbers of characters per line
start += Integer.parseInt(noc);
// Increment end variable by the selected numbers of characters per line
end += Integer.parseInt(noc);
}
// Append values into StringBuffer sb varaible by calling makeNumberedStr method
sb.append (makeNumberedStr (newdna.substring (start), start + 1));
String result = sb.toString();
for(int i = 0; i < result.length(); i++) {
}
// Check to make sure uppercase is selected, if it is then make every character uppercase, else make them lowercase
if(upperCase.isSelected()) {
DNAOutput.setText(result.toUpperCase());
} else if(lowerCase.isSelected()) {
DNAOutput.setText(result.toLowerCase());
}
}
/*
* makeNumberedStr
* This method only displays required number of characters per line
* #parameters String x and integer num
* #returns new StringBuffer value
*/
private String makeNumberedStr (String s, int num)
{
// makes and returns a string composed from left to right of:
// a 6 character field containing right justified [num] followed by 2 spaces
// the string s followed by \n
// Call new StringBuffer object and give it a length of raw dna + 8
StringBuffer sb = new StringBuffer (s.length ());
// Create nstr String varaible and give it value of num
String nstr = String.valueOf (num);
// Loop through the nstr length and append blank space
for (int i = 0 ; i < 6 - nstr.length () ; ++i)
sb.append (' ');
// Check if display number is selected, or else do not display number on every line
if(indexNum.isSelected() == true)
sb.append (nstr + " ");
// Append s value to String Buffer
sb.append (s);
// Append new line to StringBuffer
sb.append ('\n');
// Return StringBuffer text
return sb.toString();
}
Thank You, much appreciated!

Run this program, so you have a long string "s", after that i just add code(which automatically count the character's, when it counting reach's to ten, it will automatically put space between the,,), which will help you to add spaces after every ten character, even you don't need to count them...
public class PracticeOne {
public static void main(String [] args)
{
String s = "aaaaaaaaaaaaaaaaaaaaaaaaa";
System.out.println(s.replaceAll(".{10}", "$0 "));
}
}
the result is
aaaaaaaaaa aaaaaaaaaa aaaaa
hope this will help you

Without using regular expressions (which is how Akshay GOel's answer was produced) we can add spaces to a StringBuffer with a method like the one below. I think you are using 5 or 6 characters at the start of each line for a number.
//Inserts spaces every 10 characters.
//#parm from The index of the buf to begin counting to insert the spaces.
private static void addSpaces(StringBuilder buf, int from) {
for(int i=from+10; i<buf.length(); i+=11) {
buf.insert(i,' ');
// i++;
}
}

Related

Java: How to get nth letter of words in a String array

I am required to write up a static method named getSuccessiveLetters(words) that takes a string array and returns a single String. If the String array is {"hello", "world"}, then the program should return "ho". "h" is from the first word, "o" is the 2nd letter from the 2nd word and so on.
I managed to get the correct return value for {"hello", "world"}, but if the String array contains, for example,{"1st", "2nd", "3rd", "4th", "fifth"} it goes out of range it struggles.
public class Template01 {
public static void main(String[] args) {
System.out.println(getSuccessiveLetters(new String[]{"1st", "2nd", "3rd", "4th", "fifth"}));
}
public static String getSuccessiveLetters(String[] words) {
char Str[] = new char[words.length];
String successive;
for(int i = 0; i < words.length; i++){
successive = words[i];
if (i < successive.length()){
Str[i] = successive.charAt(i);
}
else
{
break;
}
}
successive = new String(Str);
return successive;
}
I expected the return value to be 1nd, but the actual output is 1nd\x00\x00.
This is happening because when you initialize a char array, it fills the array with the default char value.
You can use StringBuilder or List<Character> to grow your "array" with each addition.
Change
char[] str = new char[words.length];
to
StringBuilder str = new StringBuilder();
and
str[i] = successive.charAt(i);
to
str.append(successive.charAt(i));
and then at the end successive = str.toString();.
This is because when you ignore the strings in the original array that are not long enough, you are not setting some of the char array elements as a result. This means that some elements will have the char value of \0 (default value of char). The resulting string therefore has these extra \0 characters as well.
I think it is more suitable to use a StringBuilder rather than a char[] here:
public static String getSuccessiveLetters(String[] words) {
StringBuilder builder = new StringBuilder();
String successive;
for(int i = 0; i < words.length; i++){
successive = words[i];
if (i < successive.length()){
builder.append(successive.charAt(i));
}
// you should not break here, because there might be a longer string in the array later on.
// but apparently you don't want the "h" in "fifth"? Then I guess you should break here.
}
successive = builder.toString();
return successive;
}
I recommend using Unit-Tests here. This could help you to improve.
you are creating a charArray here:
char Str[] = new char[words.length];
this array has the length of your string-array
new String[]{"1st", "2nd", "3rd", "4th", "fifth"}
which is 5
you create 3 entries for your new array (because you break at the first word, which is too short)
therefor you get 3 letters "1nd" and the 2 other slots in your array are filled with blanks when calling
successive = new String(Str);
1st: think about the break statement
2nd: think about using a StringBuilder / StringBuffer instead of a char[] for your matches
imho the most correct result should be 1nd h - but this depends on your given task

How to specify the number of alphabets (and not blank spaces) to include in a substring?

I am trying to print a substring using index value. I need to exclude the blank space while counting but it should print the output along with blank space. I want to display, say, n alphabets from the main string. The blank spaces will be as they are but the number of alphabets from the lower bound to upper bound index should be n. My code is
public class Test {
public static void main(String args[])
{
String Str=new String("Welcome to the class");
System.out.println("\nReturn value is:");
System.out.println(Str.substring(2,9));
}
}
Output:
lcome t
In the above mentioned code, it counts the space between the "Welcome" and "to". i need not want to count the space between them. My expected output is lcome to
You could use simple mathematics. Just substring it, remove all whitespaces and compare the original length to the String without whitespaces. Afterwards add the difference in size to your end index for the substring.
public static void main(String args[]) {
String Str = "Welcome to the class";
System.out.println("\nReturn value is:");
String sub = Str.substring(2, 9);
String wsRemoved = sub.replaceAll(" ", "");
String wsBegginingRemoved = sub.replaceAll("^ *", "");
String outputSub = Str.substring(2+(sub.length()-wsBegginingRemoved.length()), 9+(sub.length()-wsRemoved.length()+(sub.length() - wsBegginingRemoved.length())));
System.out.println(outputSub);
}
Edit: not ignoring leading whitespaces anymore
O/P
lcome to
O/P "My name is Earl"
name is E
One way would be to extract it to using a regex ^.{2}([^ ] *){7}.
Another option is to use a simple for loop to traverse the string and calculate the end point to use for substring.
int non_whitespace = 0; int i;
for(i = 2; non_whitespace < 7; ++non_whitespace, ++i) {
while (str.charAt(i) == ' ') ++i;
}
return str.substring(2, i);
It is up to you which method do you consider more readable, and assess which one leads to better performance if speed is a concern.
What you want to do is display n number of characters from the string including the spaces but n doesn't include the no. of blank spaces. For that, you could simply be using a loop instead of a library function.
The Logic: Keep displaying characters of the String str from index = 2 to index = 9-1 in a while loop. If the current character is a blank space, then increase the value of n, which is the upper bound of the string index for the sub string, by 1, i.e., the program will now display an extra character beyond the upper bound for each blank space encountered.
Consider the code below.
String str = "Welcome to the class";
int index = 2, n = 9;
while(index < n){
char c = str.charAt(index);
System.out.print(c);
if(c==' ')
n++;
index++;
}
Output: lcome to
Hope you can understand this code.
EDIT
As #Finbarr O'B said, a check to prevent StringIndexOutOfBoundsException would be necessary for the program for which, the loop will have to be defined as:
while(index < n && index < str.length()){
...
}
If you don't want to use regex, you can implement your own version of substring. The straightforward solution:
private static String substring(int begin, int end, String str) {
StringBuilder res = new StringBuilder();
while (begin < end) {
if (str.charAt(begin) == ' ') {
end++;
}
res.append(str.charAt(begin));
begin++;
}
return res.toString();
}
The trick here is to ignore the "count" of a space, by incrementing end when it's encountered, forcing the loop to make one extra iteration.
The code complexity is O(n).
System.out.println(substring(2, 9, "Welcome to the class"));
>> lcome to
You could use replaceFirst for this:
String Str = "Welcome to the class"; // remove new String()
Str = Str.replaceFirst("^ *", "");
System.out.println("\nReturn value is:");
System.out.println(Str.substring(2, 10)); // increment end index by 1
Output:
lcome to

java string iterations of char variables

How do I move char characters to left or to right in a string?
Reading the input string backwards you need to keep every character on an odd index of each word and any blank characters.
You could start with this snippet. See it as a PoC to demonstrate the logic. Optimisations are possible.
String encoded = "bxoqb swi eymrawn yim";
StringBuilder decoded = new StringBuilder();
boolean keep = true;
for (int i = encoded.length() - 1; i >= 0; i--) {
if (encoded.charAt(i) != ' ') {
if (keep) {
decoded.append(encoded.charAt(i));
}
keep = !keep;
} else {
decoded.append(' ');
keep = true;
}
}
System.out.println("decoded = " + decoded);
output
decoded = my name is bob
explanation
the for-loop processes the string backwards, so the characters are processed as miy nwarmye iws bqoxb
the variable i hold the current index position in the string encoded
as we want to keep only the characters on odd positions in a word the variable keep is used as a indicator
when the variable keep is true we append the current character (the one on position i in string encoded) to the string buffer decoded
if the current processed character is not a the value of keepis negated (true->false, false->true), so we append characters on every odd position
as we need to keep between the words also we have to treat this separately, each is appended to decoded and keep is set to true so the next non-blank character would be added too
Try this:
StringBuilder builder = new StringBuilder();
String[] charArray = encoded.split(" ");
for(int i = charArray.length-1 ; i >= 0; i--){
builder.append(charArray[i]);
}
String decoded = builder.toString();
You have to use StringBuffer to reverse the sentence.Then you can split your sentence word by word using the spaces between the words. After that basic java knowledge ...
String ss = "bxoqb swi eymrawn yim";
StringBuilder buffer = new StringBuilder(ss);
String word[] = buffer.reverse().toString().split(" ");
for (String word1 : word) {
char c[]=word1.toCharArray();
for(int x=0;x<c.length;x++){
if(x%2==0){
System.out.print(c[x]);
}
}
System.out.print(" ");
}

Letter count in sentence not counting last word

I am new to java programming. This snippet calculates no of letters in each word and stores it as a string(excluding the spaces) but it is only calculating till "large" and not counting no of letters in "container".
class piSong
{
String pi = "31415926535897932384626433833";
public void isPiSong(String exp)
{
int i,count=0;
String counter = "";
String str;
System.out.println(exp.charAt(25));
for(i=0;i<exp.length()-1;i++)
{
if(Character.isWhitespace(exp.charAt(i)))
{ str = Integer.toString(count);
counter += str;
count = 0;
continue;
}
count++;
}
System.out.println(counter);
}
}
public class isPiSong{
public static void main(String[] args)
{
piSong p = new piSong();
String exp = "can i have a large container";
p.isPiSong(exp);
}
}
expected output:314157
current output: 31415
There are 2 things you should fix.
In your for loop, your condition is i<exp.length()-1. Why? You obviously want to include the last character also (which is charAt(exp.length() -1)), so you condition should either be i <= exp.length() -1 or i < exp.length().
You logic is to count the letters whenever you encounter a whitespace. But after counting the last word, you dont have a whitespace. That's why it's not counting the last word.
To Fix, append count to counter after the loop.
// Loop ends here
counter += count;
System.out.println(counter);
String counter = "";
String[] array = exp.split(" ");
for(String s: array){
counter += Integer.toString(s.length);
}
The second line splits the String into an array of strings (splits using each instance of a space in the String). The loop goes through each individual String in the array and adds its length to the counter String.
It's preferable to use a StringBuilder instead of += to append to a String.
StringBuilder sb = new StringBuilder();
String[] array = exp.split(" ");
for(String s: array){
sb.append(Integer.toString(s.length));
}
String counter = sb.toString();
But both will do the same.

Remove characters at certain position at string

I want to remove certain characters at specific positions of the String. I have the positions, but I am facing problems removing the characters.
what i am doing is:
if (string.subSequence(k, k + 4).equals("\n\t\t\t")){
string = string.subSequence(0, k) + "" + s.subSequence(k, s.length());
}
I need to remove "\n\t\t\t" from string
Use StringBuilder:
StringBuilder sb = new StringBuilder(str);
sb.delete(start, end);
sb.deleteCharAt(index);
String result = sb.toString();
Use StringBuilder
String str=" ab a acd";
StringBuilder sb = new StringBuilder(str);
sb.delete(0,3);
sb.deleteCharAt(0);
String result = sb.toString();
System.out.println(result);
public static String remove(int postion, String stringName) {
char [] charArray = stringName.toCharArray();
char [] resultArray = new char[charArray.length];
int count = 0;
for (int i=0; i< charArray.length; i++) {
if (i != postion-1) {
resultArray[count] = charArray[i];
count++;
}
}
return String.valueOf(resultArray);
}
Use String.ReplaceAll() instead of this.
But if you only want to remove specific element only you can use substring().
Now you want to know position which you already know.
Put your points in a HashSet called set
StringBuilder sb=new StringBuilder();
for(int i=0;i<string.length();i++){
if(!set.contains(string.charAt(i)))
sb.append(string.charAt(i));
}
String reformattedString=sb.toString();
First you have to put \ in front of the special characters in order to do the matching of the two string, thus you will have .equals("\"\\n\\t\\t\\t\""), otherwise the substring is not going to be recognized inside the string. Then the other thing which you have to fix is the position of the index begin and end inside .subSequence(k,k+10) since the first and the last character are 10 positions apart and not 4. Note also that when you patch the string you go from position 0 to k and from k+10 to str.length(). If you go from 0 --> k and k --> length() you just join the old string together :).
Your code should work like this, I have tested it already
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length()));
}
also you don't need +" "+ since you are adding strings. Whoever wants to see the effect of this can run this simple code:
public class ReplaceChars_20354310_part2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String str = "This is a weird string containg balndbfhr frfrf br brbfbrf b\"\\n\\t\\t\\t\"";
System.out.println(str); //print str
System.out.println(ReplaceChars(str)); //then print after you replace the substring
System.out.println("\n"); //skip line
String str2 = "Whatever\"\\n\\t\\t\\t\"you want to put here"; //print str
System.out.println(str2); //then print after you replace the substring
System.out.println(ReplaceChars(str2));
}
//Method ReplaceChars
public static String ReplaceChars (String str) {
String newstr ="";
int k;
k = str.indexOf("\"\\n\\t\\t\\t\""); //position were the string starts within the larger string
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length())); //or just str
}
return newstr;
}//end method
}

Categories

Resources