I need to get a new string based on an old one and a lag. Basically, I have a string with the alphabet (s = "abc...xyz") and based on a lag (i.e. 3), the new string should replace the characters in a string I type with the character placed some positions forward (lag). If, let's say, I type "cde" as my string, the output should be "fgh". If any other character is added in the string (apart from space - " "), it should be removed. Here is what I tried, but it doesn't work :
String code = "abcdefghijklmnopqrstuvwxyzabcd"; //my lag is 4 and I added the first 4 characters to
char old; //avoid OutOfRange issues
char nou;
for (int i = 0; i < code.length() - lag; ++i)
{
old = code.charAt(i);
//System.out.print(old + " ");
nou = code.charAt(i + lag);
//System.out.println(nou + " ");
// if (s.indexOf(old) != 0)
// {
s = s.replace(old, nou);
// }
}
I commented the outputs for old and nou (new, but is reserved word) because I have used them only to test if the code from position i to i + lag is working (and it is), but if I uncomment the if statement, it doesn't do anything and I leave it like this, it keeps executing the instructions inside the for statmement for code.length() times, but my string doesn't need to be so long. I have also tried to make the for statement like below, but I got lost.
for (int i = 0; i < s.length(); ++i)
{
....
}
Could you help me with this? Or maybe some advices about how I should think the algorithm?
Thanks!
It doesn't work because, as the javadoc of replace() says:
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
(emphasis mine)
So, the first time you meet an 'a' in the string, you replace all the 'a's by 'd'. But then you go to the next char, and if it's a 'd' that was an 'a' before, you replace it once again, etc. etc.
You shouldn't use replace() at all. Instead, you should simply build a new string, using a StringBuilder, by appending each shifted character of the original string:
String dictionary = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
char oldChar = input.charAt(i);
int oldCharPositionInDictionary = dictionary.indexOf(oldChar);
if (oldCharPositionInDictionary >= 0) {
int newCharPositionInDictionary =
(oldCharPositionInDictionary + lag) % dictionary.length();
sb.append(dictionary.charAt(newCharPositionInDictionary));
}
else if (oldChar == ' ') {
sb.append(' ');
}
}
String result = sb.toString();
Try this:
Convert the string to char array.
iterate over each char array and change the char by adding lag
create new String just once (instead of loop) with new String passing char array.
String code = "abcdefghijklmnopqrstuvwxyzabcd";
String s = "abcdef";
char[] ch = s.toCharArray();
char[] codes = code.toCharArray();
for (int i = 0; i < ch.length; ++i)
{
ch[i] = codes[ch[i] - 'a' + 3];
}
String str = new String(ch);
System.out.println(str);
}
My answer is something like this.
It returns one more index to every character.
It reverses every String.
Have a good day!
package org.owls.sof;
import java.util.Scanner;
public class Main {
private static final String CODE = "abcdefghijklmnopqrstuvwxyz"; //my lag is 4 and I added the first 4 characters to
#SuppressWarnings("resource")
public static void main(String[] args) {
System.out.print("insert alphabet >> ");
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
char[] char_arr = s.toCharArray();
for(int i = 0; i < char_arr.length; i++){
int order = CODE.indexOf(char_arr[i]) + 1;
if(order%CODE.length() == 0){
char_arr[i] = CODE.charAt(0);
}else{
char_arr[i] = CODE.charAt(order);
}
}
System.out.println(new String(char_arr));
//reverse
System.out.println(reverse(new String(char_arr)));
}
private static String reverse (String str) {
char[] char_arr = str.toCharArray();
for(int i = 0; i < char_arr.length/2; i++){
char tmp = char_arr[i];
char_arr[i] = char_arr[char_arr.length - i - 1];
char_arr[char_arr.length - i - 1] = tmp;
}
return new String(char_arr);
}
}
String alpha = "abcdefghijklmnopqrstuvwxyzabcd"; // alphabet
int N = alpha.length();
int lag = 3; // shift value
String s = "cde"; // input
StringBuilder sb = new StringBuilder();
for (int i = 0, index; i < s.length(); i++) {
index = s.charAt(i) - 'a';
sb.append(alpha.charAt((index + lag) % N));
}
String op = sb.toString(); // output
Related
so I have task to double number of letter "a" every time it occurs in a string.
For example sentence "a cat walked on the road" , at the end must be "aa caaaat waaaaaaaalked on the roaaaaaaaaaaaaaaaa" . I had something like this on my mind but it doubles every charachter, not only "a".
public static void main(String[] args) {
String s = "a bear walked on the road";
String result = "";
int i = 0;
while(i<s.length()){
char a = s.charAt(i);
result = result + a + a;
i++;
}
System.out.println(result);
}
You need to check what the char a is (in your case, 'a'). Additionally, you do not repeat the characters more than twice in your code, hence not getting the answer you expected: result = result + a + a only adds 'a' twice, not giving you: "aa caaaat waaaaaaaalked...".
Here is the solution:
public static void main(String[] args) {
String s = "a bear walked on the road";
String result = "";
char lookingFor = 'a'; // Can change this to whatever is needed
int counter = 2;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == lookingFor) { // The current character is what we need to be repeated.
// Repeat the character as many times as counter is (each loop: 2, 4, 6, 8, ...)
for (int j = 0; j < counter; j++) {
result += lookingFor;
}
counter *= 2; // Double counter at every instance of 'a'
}
else { // The current char is not what we are looking for, so we just add it to our result.
result += s.charAt(i);
}
}
System.out.println(result);
}
The problems are:
you are doubling every character because you are not testing if it is an 'a' or not.
and you are not doubling the substitution each time.
Here is a modified version of your solution.
String s = "a bear walked on the road";
String result = "";
String sub = "aa";
int i = 0;
while(i<s.length()){
// get the character
char ch = s.charAt(i++);
//if it an a, append sub to result
// and double sub.
if (ch == 'a') {
result += sub;
sub += sub;
} else {
// otherwise, just append the character
result += ch;
}
}
Here is another way.
check each character and double the replacement each time an a is encountered.
String str = "a cat walked on the road";
StringBuilder sb = new StringBuilder();
String sub = "a";
for (String s : str.split("")) {
sb.append(s.equals("a") ? (sub += sub) : s);
}
System.out.println(sb);
prints
aa caaaat waaaaaaaalked on the roaaaaaaaaaaaaaaaad
Try this out:
public static void main(String[] args) {
char letterToSearch = 'a'
String myString = "a bear walked on the road";
StringBuilder result = new StringBuilder();
int occurrance = 0;
for (int i = 0; i < myString.length(); i++){
char currChar = myString.charAt(i);
if (currChar == letterToSearch){
occurrance+=1;
for (int j = 0; j < 2*occurrance; j++){
result.append(currChar);
}
} else {
result.append(currChar);
}
}
System.out.println(result);
}
The variable occurrance keeps track of how many as you have.
I am new to programming I need to reverse a string without using the library function.
I am able to reverse but as expected.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
String rev = "";
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<String> splitResult = new ArrayList<String>();
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == ' ')
list.add(i);
list.add(0, 0);
list.add(list.size(), s.length());
String[] words = new String[list.size()];
for (int j = 0; j <= words.length - 2; j++)
splitResult.add(s.substring(list.get(j), list.get(j + 1)).trim());
System.out.println(splitResult);
String[] str = new String[splitResult.size()];
str = splitResult.toArray(str);
for (int i = 0; i < str.length; i++) {
if (i == str.length - 1) {
rev = str[i] + rev;
} else {
rev = " " + str[i] + rev;
}
}
System.out.println(rev);
Expected:
Input: i am coder
output: redoc ma i
actual
input: i am coder
output: coder am i
You can just provide an empty result variable, iterate the characters of the given String by using an enhanced for-loop (also known as for-each loop) setting every character to index 0 of the result variable by just concatenating the character to the result variable like this:
public static void main(String[] args) {
// input
String s = "I am coder";
// result variable for reverse input
String reverseS = "";
// go through every single character of the input
for (char c : s.toCharArray()) {
// and concatenate it and the result variable
reverseS = c + reverseS;
}
// then print the result
System.out.println(reverseS);
}
You can of course do that in a slightly different way using a classic for-loop and the length of the input, see this example:
public static void main(String[] args) {
String s = "I am coder";
String reverseS = "";
for (int i = 0; i < s.length(); i++) {
reverseS = s.charAt(i) + reverseS;
}
System.out.println(reverseS);
}
String s = "I am coder";
String rev="";
for (int i = s.length()-1; i >=0; i--) {
rev+=s.charAt(i);
}
System.out.println(rev);
I have set the index I to the last character of the given string and the condition is set to 0(i.e the first character). Hence the loop runs from the last character to the first character. It extracts each of the characters to a given new String. Hope it helps!
You can just take another list go from last to first and display like this
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
ArrayList<Character> working = new ArrayList<Character>();
ArrayList<Character> finished = new ArrayList<Character>();
for (char ch: s.toCharArray()) {
working.add(ch);
}
for(int i = working.size() - 1 ; i>=0 ; i--){
finished.add(working.get(i));
}
for(int j = 0 ; j < finished.size() ; j++){
System.out.print(finished.get(j));
}
public String getEncryption(String text){
String x = "";
for(int i = 0; i < text.length(); i++){
String sub = text.substring(i, i+1);
System.out.println(i + " = " + sub);
String en = encrypt_code[Integer.parseInt(sub)];
System.out.println("Result:" + en);
x = x.concat(en);
}
return x;
}
I have this coding which works perfectly but I need to know how to use the charAt method to convert this and works in the same way? I have this so far
public String getEncryption2(String text){
String x = "";
for(int i = 0; i < text.length(); i++){
char ch = text.charAt(i);
You're reading every char as a substring, and parse it as an int. So, you get for example "4" as the substring, and parse it to get the int 4.
If you use charAt(), you'll get the char '4' instead. To transform it to the integer 4, you just need to subtract '0' from it:
String en = encrypt_code[ch - '0'];
Note that replacing the whole string by a new one at each iteration is time consuming. You should use a StringBuilder instead:
StringBuilder x = new StringBuilder();
for (...) {
x.append(en);
}
return x.toString();
Im trying to reverse characters in a sentence without using the split function. Im really close but I am missing the final letter. Can some one please point me in the right direction? Right now it prints "This is a new sentence" as "sihT si a wen cnetnes" Also I included if(start == 0) because the program would skip the initial space character, but I don't understand why?
static String reverseLetters(String sentence)
StringBuilder reversed = new StringBuilder("");
int counter = 0;
int start = 0;
String word;
for(int i = 0; i <= sentence.length()-1 ; i++ )
{
if(sentence.charAt(i)== ' '|| i == sentence.length()-1 )
{
StringBuilder sb = new StringBuilder("");
sb.append(sentence.substring(start,i));
if(start == 0)
{
start = i;
word = sb.toString();
reversed.append(reverseChar(word));
reversed.append(' ');
}
else
{
start = i;
word = sb.toString();
reversed.append(reverseChar(word));
}
}
return reversed.toString();
}
static String reverseChar (String word)
{
StringBuilder b = new StringBuilder("");
for(int idx = word.length()-1; idx >= 0; idx -- )
{
b.append(word.charAt(idx));
}
return b.toString();
}
start means wordStart. As i points to the space, the next wordStart should point after i.
Hence the last i should point after the last word char, should be length()
the if-then-else is too broad; a space has to be added in one case: i pointing at the space.
One could loop unconditionally, and on i == length() break in the middle of the loop code.
I think the error lies in the index, the for should be
for(int i = 0; i <= sentence.length() ; i++ )
Then if should be:
if (sentence.charAt(i==0?0:i-1)== ' '|| i == sentence.length() )
For me the error will be that the substring(start,i) for the last one i should be sentence.length instead of sentence.length-1, so this would solve it.
Substring is open in the last index, so if you put substring(1, 10) will be substring from 1 to 9. That might be the problem with last word.
The thing with the first space is also the problem with substring, let's say you're reading "this is..." the first time it will do a subtring with start=0 and i = 4 so you expect "this " but it really is "this". The next reading, with start=4 and i=7 will be " is".
So with the change of the index you should be able to remove the if/else with start==0 too.
Another option
private String reverse (String originalString) {
StringBuilder reverseString = new StringBuilder();
for (int i = originalString.length() - 1; i >= 0; i--) {
reverseString.append(originalString.charAt(i));
}
return reverseString.toString();
}
String reverseString = "This is a new sentence";
System.out.println(new StringBuffer(reverseString).reverse().toString());
Syso prints : ecnetnes wen a si sihT
Put
i <= sentence.length()
In your for loop and change the if to:
if(i == sentence.length() || sentence.charAt(i)== ' ')
as
substring(start,i)
Returns the string up to i, not included.
import java.util.Stack;
public class Class {
public static void main(String[] args) {
String input = "This is a sentence";
char[] charinput = input.toCharArray();
Stack<String> stack = new Stack<String>();
for (int i = input.length() - 1; i >= 0; i--) {
stack.push(String.valueOf(charinput[i]));
}
StringBuilder StackPush = new StringBuilder();
for (int i = 0; i < stack.size(); i++) {
StackPush.append(stack.get(i));
}
System.out.println(StackPush.toString());
}
}
Not a split to be seen.
I have no idea how to start my assignment.
We got to make a Run-length encoding program,
for example, the users enters this string:
aaaaPPPrrrrr
is replaced with
4a3P5r
Can someone help me get started with it?
Hopefully this will get you started on your assignment:
The fundamental idea behind run-length encoding is that consecutively occurring tokens like aaaa can be replaced by a shorter form 4a (meaning "the following four characters are an 'a'"). This type of encoding was used in the early days of computer graphics to save space when storing an image. Back then, video cards supported a small number of colors and images commonly had the same color all in a row for significant portions of the image)
You can read up on it in detail on Wikipedia
http://en.wikipedia.org/wiki/Run-length_encoding
In order to run-length encode a string, you can loop through the characters in the input string. Have a counter that counts how many times you have seen the same character in a row. When you then see a different character, output the value of the counter and then the character you have been counting. If the value of the counter is 1 (meaning you only saw one of those characters in a row) skip outputting the counter.
public String runLengthEncoding(String text) {
String encodedString = "";
for (int i = 0, count = 1; i < text.length(); i++) {
if (i + 1 < text.length() && text.charAt(i) == text.charAt(i + 1))
count++;
else {
encodedString = encodedString.concat(Integer.toString(count))
.concat(Character.toString(text.charAt(i)));
count = 1;
}
}
return encodedString;
}
Try this one out.
This can easily and simply be done using a StringBuilder and a few helper variables to keep track of how many of each letter you've seen. Then just build as you go.
For example:
static String encode(String s) {
StringBuilder sb = new StringBuilder();
char[] word = s.toCharArray();
char current = word[0]; // We initialize to compare vs. first letter
// our helper variables
int index = 0; // tracks how far along we are
int count = 0; // how many of the same letter we've seen
for (char c : word) {
if (c == current) {
count++;
index++;
if (index == word.length)
sb.append(current + Integer.toString(count));
}
else {
sb.append(current + Integer.toString(count));
count = 1;
current = c;
index++;
}
}
return sb.toString();
}
Since this is clearly a homework assignment, I challenge you to learn the approach and not just simply use the answer as the solution to your homework. StringBuilders are very useful for building things as you go, thus keeping your runtime O(n) in many cases. Here using a couple of helper variables to track where we are in the iteration "index" and another to keep count of how many of a particular letter we've seen "count", we keep all necessary info for building our encoded string as we go.
Try this out:
private static String encode(String sampleInput) {
String encodedString = null;
//get the input to a character array.
// String sampleInput = "aabbcccd";
char[] charArr = sampleInput.toCharArray();
char prev=(char)0;
int counter =1;
//compare each element with its next element and
//if same increment the counter
StringBuilder sb = new StringBuilder();
for (int i = 0; i < charArr.length; i++) {
if(i+1 < charArr.length && charArr[i] == charArr[i+1]){
counter ++;
}else {
//System.out.print(counter + Character.toString(charArr[i]));
sb.append(counter + Character.toString(charArr[i]));
counter = 1;
}
}
return sb.toString();
}
Here is my solution in java
public String encodingString(String s){
StringBuilder encodedString = new StringBuilder();
List<Character> listOfChars = new ArrayList<Character>();
Set<String> removeRepeated = new HashSet<String>();
//Adding characters of string to list
for(int i=0;i<s.length();i++){
listOfChars.add(s.charAt(i));
}
//Getting the occurance of each character and adding it to set to avoid repeated strings
for(char j:listOfChars){
String temp = Integer.toString(Collections.frequency(listOfChars,j))+Character.toString(j);
removeRepeated.add(temp);
}
//Constructing the encodingString.
for(String k:removeRepeated){
encodedString.append(k);
}
return encodedString.toString();
}
import java.util.Scanner;
/**
* #author jyotiv
*
*/
public class RunLengthEncoding {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter line to encode:");
Scanner s=new Scanner(System.in);
String input=s.nextLine();
int len = input.length();
int i = 0;
int noOfOccurencesForEachChar = 0;
char storeChar = input.charAt(0);
String outputString = "";
for(;i<len;i++)
{
if(i+1<len)
{
if(input.charAt(i) == input.charAt(i+1))
{
noOfOccurencesForEachChar++;
}
else
{
outputString = outputString +
Integer.toHexString(noOfOccurencesForEachChar+1) + storeChar;
noOfOccurencesForEachChar = 0;
storeChar = input.charAt(i+1);
}
}
else
{
outputString = outputString +
Integer.toHexString(noOfOccurencesForEachChar+1) + storeChar;
}
}
System.out.println("Encoded line is: " + outputString);
}
}
I have tried this one. It will work for sure.