Let's say I have a string with the phrase "Bank of America". I want to reverse it so the output results in "aciremA fo knaB"
This is the code I have been trying to use but the output is only the last letter of the last word, which would be "a"
int position = phraseLength;
for(int index = position-1; index >= 0; index--);
System.out.println(p1.charAt(position-1));
I am not sure what is wrong here so any help would be appericated.
StringBuffer sb=new StringBuffer("Bank of America");
System.out.println(sb.reverse());
If you want to do it your way. use
int position = phraseLength;
for(int index = position-1; index >= 0; index--)
System.out.println(p1.charAt(index));
You have added an extra semicolon after for loop here
for(int index = position-1; index >= 0; index--);
^
Also you are always accessing the postion-i. You should access the index
System.out.println(p1.charAt(position-1));
^^^^^^^^^^^
here
You can use this
int position = phraseLength;
for(int index = position-1; index >= 0; index--)
System.out.print(p1.charAt(index));
or this
String output = "";
int position = phraseLength;
for(int index = position-1; index >= 0; index--)
output+=p1.charAt(index);
System.out.println(output);
public String reverse(String str) {
char [] buffer = str.toCharArray();
for (int i = 0, j = buffer.length - 1; i < j; i++, j--) {
char temp = buffer[i];
buffer[i] = buffer[j];
buffer[j] = temp;
}
return new String(buffer);
}
I guess by mistake you have added the semicolon after for loop. Practically this will not give any compile time error. But the content of the loop will be executed only once. So remove the semicolon and get it done !!
StringBuffer stringBuffer=new StringBuffer("Bank of America");
System.out.println(stringBuffer.reverse());
Declare a string.
Take out the length of that string.
Loop through the characters of the string.
Add the characters in reverse order in the new string.
String str = "hello";
String reverse = "";
int length = str.length();
for (int i = 0; i < length; i++) {
reverse = str.charAt(i) + reverse;
}
System.out.println(reverse);
Related
here is the code. I keep getting the error: String index out of range:5, I don't know what I'm doing wrong so any help will be appreciated. Also, I'm not allowed to use any Scanner class methods other than length.
import java.util.*;
public class capitalLetter
{
public static void main(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a non capitalized word");
String word = sc.next();
int length = word.length();
char ch[] = new char[length];
for(int i = 0;i<length-1;i++){
ch[length] = word.charAt(length);
}
ch[0]+=32;
for(int i = 0;i<length-1;i++){
System.out.print(ch[length]);
}
}
}
Firstly, within the for loop you need to use the loop variable i, rather than length. Also, i should go to the last element of the array.
This
for(int i = 0; i < length-1; i++){
ch[length] = word.charAt(length);
}
should be
for(int i = 0; i < length; i++){
ch[i] = word.charAt(i);
}
Secondly, you're adding 32 when you should be subtracting.
Putting this together you get:
String word = "hello";
int length = word.length();
char ch[] = new char[length];
for(int i = 0; i < length; i++) {
ch[i] = word.charAt(i);
}
ch[0] -= 32;
for(int i = 0; i < length; i++) {
System.out.print(ch[i]);
}
Output:
Hello
In both of your loops, you are indexing by length instead of by i.
e.g this line
ch[length] = word.charAt(length);
should be like this
ch[i] = word.charAt(i);
I got this problem in my programming competency test. I need to find the exponent of a string.
For Eg :
Input Str = "pctpctpct", output : pct 3.
Input str : "pressure", output 0. Because pressure is not repeating as a string.
That is the string pct is repeated 3 times.
I need to create a method for this. I tried everything but failed.
My method was :
public static int findExponent(String str) {
int count = 0;
String subs = "";
ArrayList<String> al = new ArrayList<String>();
for (int i = 0; i < str.length() / 2; i++) {
for (int j = i + 1; j <= str.length() / 2; j++) {
subs = str.substring(i, j);
al.add(subs);
System.out.println(al);
for (String x : al)
for (int k = 0; k < str.length(); k++) {
if (str.contains(x)) {
count++;
}
}
}
}
return count;
}
Here I was checking if any substring matches the pattern of the String. But it is not giving me the correct output. What changes should I need to do in this?
How to check the pattern for such a type of question where we have to create a pattern and check if it's repeated?
How about this. I would go ahead with the algorithm based on java:-
Lets assume the input is the string
convert it to character sequence (array of char)
Sort the array into a temp array
loop from 0 to array length
count the ith letter repetition
if its 0
return 0;
else
if count for all word matches
return count;
complexity is 0(n) and this code would work
I am trying to make an application that will reverse a string using a while loop. Just wondering if I am on the right path or not.
So I thought I would make a while loop to determine how many chars i should make. Then I would just print them in reverse in the console.
Here is my code so far. Any help would be appreciated.
// Get the text from the input from the user
// Outputs it to the Text area
// Uses while loop to calculate how many chars to create
String Startword = txfInput.getText();
int LengthOfWord = Startword.length();
int Counter = 1;
while (Counter <= LengthOfWord)
{
// Creates amounts of chars based off the counter
Counter = Counter +1 ;
}
Any suggestions?
Just use a for loop..
String reverse = "";
for (int i = word.length()-1; i>=0; i--)
{
reverse += word.charAt(i);
}
if you want a while... then
while(i >= 0)
{
reverse += word.charAt(i);
i--;
}
You just need to add a character to the reverse String after every iteration, like this:
String Startword = txfInput.getText();
String rev="";
int LengthOfWord = Startword.length();
int Counter = 1;
while (Counter <= LengthOfWord)
{
rev=Startword.charAt(Counter-1)+rev; // Add a character to rev.
Counter = Counter +1 ;
}
System.out.println(rev);
Might be easier to do with a char array:
char[] output = new char[Startword.length];
for(int i = 0; i < Startword.length; i++){
output[i] = Startword.charAt(Startword.length - i - 1);
}
String rev = new String(output);
Scanner input = new Scanner(System.in);
String s=input.nextLine();
char[] stringArray;
stringArray = s.toCharArray();
int temp;
int low=0;
int high=stringArray.length-1;
while(low<high){
temp= stringArray[low];
stringArray[low] = stringArray[high];
System.out.print(stringArray[low]);
low ++;
high--;
}
check this out
The String word contains a character ] at more than one place. I want to replace any character before the ] by l, and any character after by r.
For example, the String defined below:
String word="S]RG-M]P";
Should be converted to:
String word="l]rG-l]r";
When I tried by the following code:
String word="S]RG-M]P";
char[] a = word.toCharArray();
for(int i=0; i<a.length; i++){
if (a[i]==']'){
a[i+1]='r';
a[i-1]='l';
}
}
It changes the right side of ] by r, but fails left to it by l. I need help to get the required results.
public static void main(String[] args) {
String word = "S]RG-M]P";
char[] a = word.toCharArray();
for (int i = 1; i < a.length-1; i++) {//#Jon Skeet again is right X2 :)
//no need now, for loop bound changed
//if(i+1>a.length){
// continue;
// }
if (a[i] == ']') {
//no need now, for loop bound changed
//#Jon Skeet you are right, this handles the case :)
//if(i==0 || i == a.length-1){
//continue;
//}
a[i + 1] = 'r';
a[i - 1] = 'l';
}
}
String outt = new String(a);
System.out.print(outt);
}// main
StringBuilder word = new StringBuilder("S]RG-M]P");
int index = word.indexOf("]");
while(index > 0){
word.setCharAt(index-1, 'l');
word.setCharAt(index+1, 'r');
index = word.indexOf("]", index+1);
}
System.out.println(word);
String word="S]RG-M]P";
word.replaceAll(".]." , "l]r");
using regex and string methods is useful in this situation
for(int i=0 ; i<word.length();i++){
char a = word.charAt(i);
String after =null;
if( Character.toString(a).equals("]")){
int j = i-1;
int k = i+1;
char b = word.charAt(j);
char c = word.charAt(k);
modifyword= word.replace( Character.valueOf(b).toString(), "l");
after= modifyword.replace( Character.valueOf(c).toString(), "r");
word = after;
}
}
I've got an String ("Dinosaur") and I don't exactly know how, but how do I get the position of the char "o" and is it in all possible to get two positions like if my String was ("Pool")
As for your first question, you can use String#indexOf(int) to get the index of every 'o' in your string.
int oPos = yourString.indexOf('o');
As for your second question, it is possible to get all positions of a given char by making a method which uses String.indexOf(int, int), tracking the previous index so that you don't repeat searched portions of the string. You could store the positions in an array or list.
Use indexOf with a loop:
String s = "Pool";
int idx = s.indexOf('o');
while (idx > -1) {
System.out.println(idx);
idx = s.indexOf('o', idx + 1);
}
Simply:
public static int[] getPositions(String word, char letter)
{
List<Integer> positions = new ArrayList<Integer>();
for(int i = 0; i < word.length(); i++) if(word.charAt(i) == letter) positions.add(i);
int[] result = new int[positions.size()];
for(int i = 0; i < positions.size(); i++) result[i] = positions.get(i);
return result;
}
This is probably going a little over board, but hey ;)
String master = "Pool";
String find = "o";
Pattern pattern = Pattern.compile(find);
Matcher matcher = pattern.matcher(master);
String match = null;
List<Integer[]> lstMatches = new ArrayList<Integer[]>(5);
while (matcher.find()) {
int startIndex = matcher.start();
int endIndex = matcher.end();
lstMatches.add(new Integer[] {startIndex, endIndex});
}
for (Integer[] indicies : lstMatches) {
System.out.println("Found " + find + " # " + indicies[0]);
}
Gives me
Found o # 1
Found o # 2
The great thing is, you could also find "oo" as well
Have you tried converting the String to a char array?
int counter = 0;
String input = "Pool";
for(char ch : input.toCharArray()) {
if(ch == 'o') {
System.out.println(counter);
}
counter += 1;
}
Try this
String s= "aloooha";
char array[] = s.toCharArray();
Stack stack = new Stack();
for (int i = 0; i < array.length; i++) {
if(array[i] == 'o'){
stack.push(i);
}
}
for (int i = 0; i < stack.size(); i++) {
System.out.println(stack.get(i));
}