Finding all uppercase letters of a string in java - java

So I'm trying to find all the uppercase letters in a string put in by the user but I keep getting this runtime error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)
I feel foolish but I just can't figure this out and oracle even talks about charAt on the page about java.lang.StringIndexOutOfBoundsException
Here is my code for finding the uppercase letters and printing them:
import java.io.*;
import java.util.*;
public class P43{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//Uppercase
String isUp = "";
System.out.print("Please give a string: ");
String x = in.next();
int z = x.length();
for(int y = 0; y <= z; y++){
if(Character.isUpperCase(x.charAt(y))){
char w = x.charAt(y);
isUp = isUp + w + " ";
}
}
System.out.println("The uppercase characters are " + isUp);
//Uppercase
}
}
I'd really appreciate any input and or help.

for(int y = 0; y <= z; y++){
should be
for(int y = 0; y < z; y++){
Remember array index starts from ZERO.
String length returns
the number of 16-bit Unicode characters in the string
Because loop started from ZERO, loop should terminate at length-1.

The array index out of bounds is due to the for loop not terminating on length - 1, it is terminating on length
Most iterating for loops should be in the form:
for (int i = 0; i < array.length; i++) {
// access array[i];
}
It's the same with a string.
Perhaps a cleaner way would be:
String inputString; // get user input
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
outputString += Character.isUpperCase(c) ? c + " " : "";
}
System.out.println(outputString);
Edit: Forgot String Doesn't implement Iterable<Character>, silly Java.

With Java 8 you can also use lambdas. Convert the String into a IntStream, use a filter to get the uppercase characters only and create a new String by appending the filtered characters to a StringBuilder:
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
//Uppercase
String isUp = in.next()
.chars()
.filter(Character::isUpperCase)
.collect(StringBuilder::new, // supplier
StringBuilder::appendCodePoint, // accumulator
StringBuilder::append) // combiner
.toString();
System.out.println("The uppercase characters are " + isUp);
//Uppercase
Inspired by:
Adam Bien - Streaming A String
Simplest way to print anIntStream as a String

Try this...
Method:
public int findUpperChar(String valitateStr) {
for (int i = valitateStr.length() - 1; i >= 0; i--) {
if (Character.isUpperCase(valitateStr.charAt(i))) {
return i;
}
}
return -1;
}
Usage:
String passwordStr = password.getText().toString();
.......
int len = findUpperChar(passwordStr);
if ( len != -1) {
capitals exist.
} else {
no capitals exist.
}

Hi one of the easy step to find uppercase char in a given string...
Program
import java.io.*;
public class testUpper
{
public static void main(String args[]) throws IOException
{
String data,answer="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any String : ");
data=br.readLine();
char[] findupper=data.toCharArray();
for(int i=0;i<findupper.length;i++)
{
if(findupper[i]>=65&&findupper[i]<=91) //ascii value in between 65 and 91 is A to Z
{
answer+=findupper[i]; //adding only uppercase
}
}
System.out.println("Answer : "+answer);
}
}
Output
Enter any String :
Welcome to THe String WoRlD
Answer : WTHSWRD

You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, I suggest importing the least number of libraries into your class. Please avoid using .* while importing.
import java.util.Scanner;
public class P43 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
String x = in.next();
x.chars().filter(c -> Character.isUpperCase(c))
.forEach(c -> System.out.print((char) c + " "));
}
}
Sample input:
saveChangesInTheEditor
Sample output:
C I T E

import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
StringBuilder s=new StringBuilder();
Scanner input = new Scanner(System.in);
System.out.println("Enter your String");
String str= input.nextLine();
for(int i=0; i<str.length(); i++)
{
if(Character.isUpperCase(str.charAt(i)))
{
System.out.print(str.charAt(i)+" ");
}
}
}
}

The simplest way I know is to use regex replacement.
isUp = x.replaceAll("[^A-Z]", "");
In simple terms, this uses a regular expression which matches any character which is not in the A-Z range, and replaces it with an empty string.

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
String str= input.nextLine();
int ascii;
for(int i=0; i<str.length(); i++) {
ascii = str.charAt(i);
System.out.println(ascii);
if (ascii >= 65 && ascii <= 90) {
System.out.println("captal letter found ::: "+ascii);
}
}
}

public class Cama {
public static void main(String[] args) {
String camal = "getStudentByName";
String temp = "";
for (int i = 0; i < camal.length(); i++) {
if (Character.isUpperCase(camal.charAt(i))) {
System.out.print(" " + Character.toLowerCase(camal.charAt(i)));
} else if (i == 0) {
System.out.print(Character.toUpperCase(camal.charAt(i)));
}else{
System.out.print(camal.charAt(i));
}
}
}
}

Related

Removing negative sign from a string

I have to reverse the string a user inputs and I'm trying to remove the negative sign when a user enters a negative number but I'm unsure of how to go about this.
I've tried using string.replace() but I instead of printing for example "9" when a user entered "-9", it would return "99-9"
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
System.out.println("Type a number: ");
String num = scnr.nextLine();
String reverse = "";
for (int i = num.length() - 1; i >= 0; i--) {
reverse = reverse + num.charAt(i);
}
System.out.println("Reverse is: " + reverse);
}
}
The straight forward solution: put an if block in your loop!
You are right now adding characters unconditionally. You could for example only append characters that are digits. Then any other thing, like a '-' won't show up in your output!
You can try something like this.
public class App {
public static void main(String[] args) {
String input = "78-889-969-*)(963====";
StringBuilder builder = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--) {
if (input.charAt(i) >= 48 && input.charAt(i) <= 57) {
builder.append(input.charAt(i));
}
}
System.out.println("builder = " + builder.toString());
}
}
Using Character.isDigit()
public class App {
public static void main(String[] args) {
String input = "78-889-969-*)(963====";
StringBuilder builder = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--) {
if (Character.isDigit(input.charAt(i))) {
builder.append(input.charAt(i));
}
}
System.out.println("builder = " + builder.toString());
}
}
Replace the for loop with the below.
for (int i = num.length() - 1; i >= 0; i--)
{
if(num.charAt(i) == 45){
break;
}
reverse = reverse + num.charAt(i);
}`
45 is the ASCII value of - sign. The if(num.charAt(i) == 45) checks if there is - sign and if so it breaks the loop before it prints the - sign.
Note - The loop will not break till it reaches i = 0.

I want to display the occurrence of a character in string. How can I improve my code? [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 4 years ago.
Improve this question
I want to create a program that will display the number of occurrences of a character in a string and also count them. Right now the code just counts the characters.
I want to make the following changes:
1) How do I make this program only count one type of a character, like a or c in a string I love ice cream.
2) How do I also print the character in a string, let's say there are two d my program will then display 2 d first.
3) For the Scanner input = new Scanner(System.in); part I get error in my eclipse, says scanner cannot be resolved to a type.
Also feel free to comment on anything need to be improved in the code. Basically just want a simple program to display all the C in a string and then count the string's occurrence. I want to then mess around the code on my own, change it so I can learn Java.
So this is my code so far:
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < length; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str);
}
}
Try this
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
// Whatever is the input it take the first character.
char searchKey = input.nextLine().charAt(0);
countString(str, searchKey);
}
public static void countString(String str, char searchKey) {
// The count show both number and size of occurrence of searchKey
String count = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count += str.charAt(i) + "\n";
}
System.out.println(count + "\nNumber of Occurrence of "
+ searchKey + " is " + count.length() + " in string " + str);
}
You could utilize the fact that each char can be used as an index into an array and use an array to count up each character.
public class Count {
static final int MAX_CHAR = 256;
private static void countString(String str, Character character) {
int [] counts = new int[MAX_CHAR];
char [] chars = str.toCharArray();
for (char ch : chars) {
if (character!=null && character!=ch) {
continue;
}
counts[ch]++;
}
for (int i=0; i<counts.length; i++) {
if (counts[i]>0) {
System.out.println("Character " + (char)i + " appeared " + counts[i] + " times");
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
countString(str, 'e');
}
}
you can take input from user "which character he/she wants to count".
To show the occurrence of character see code below.
You need to import java.util.Scanner class.
Here is your code:
import java.util.Arrays;
import java.util.Scanner;
public class Count {
public static void countString(String str)
{
if(str!=null) {
int length = str.length();
// Create an array of given String size
char ch[] = str.toCharArray();
Arrays.sort(ch);
if(length>0) {
char x = ch[0];
int count = 1;
for(int i=1;i<length; i++) {
if(ch[i] == x) {
count++;
} else {
System.out.println("Number of Occurrence of '" +
ch[i-1] + "' is: " + count);
x= ch[i];
count = 1;
}
}
System.out.println("Number of Occurrence of '" +
ch[length-1] + "' is: " + count);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();//"geeksforgeeks";
countString(str);
}
}
See the snippet below for a way to do it in Java8
public static void main(String[] args) {
// printing all frequencies
getCharacterFrequency("test")
.forEach((key,value) -> System.out.println("Key : " + key + ", value: " + value));
// printing frequency for a specific character
Map<Character, Long> frequencies = getCharacterFrequency("test");
Character character = 't';
System.out.println("Frequency for t: " +
(frequencies.containsKey(character) ? frequencies.get(character): 0));
}
public static final Map<Character, Long> getCharacterFrequency(String string){
if(string == null){
throw new RuntimeException("Null string");
}
return string
.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
You just have to modify this line of code:
using for loop, print str.charAt(i) for count[str.charAt(i) times in your if statement.
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
Edit: modified based on your comment, if you want the whole code
import java.util.*;
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < length; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j]){
//System.out.println(str.charAt(i));
find++;
}
}
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksfeorgeeks";
str = input.nextLine();
countString(str);
}
}
output
g,g,2
e,e,e,e,e,5
k,k,2
s,s,2
f,1
o,1
r,1
I know you are beginner but if you want to try new version java 8 features which makes our coding life simple and easier you can try this
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
List<String> l = Arrays.asList(str.split(""));
// prints count of each character occurence in string
l.stream().forEach(character->System.out.println("Number of Occurrence of " +
character + " is:" + Collections.frequency(l, character)));
if(!(Character.toString(value).isEmpty())) {
// prints count of specified character in string
System.out.println("Number of Occurrence of " +
value + " is:" + Collections.frequency(l, Character.toString(value)));
}
}
And this is the code with requirements mentioned in comments
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
String[] arr = str.split("");
StringBuffer tempString = new StringBuffer();
for(String s:arr) {
tempString.append(s);
for(char ch:s.toCharArray()) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString.chars().filter(i->i==ch).count());
}
}
if(!(Character.toString(value).isEmpty())) {
StringBuffer tempString2 = new StringBuffer();
for(String s:arr) {
tempString2.append(s);
for(char ch:s.toCharArray()) {
if(ch==value) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString2.chars().filter(i->i==ch).count());
}
}
}
}
}
}
You can use this code below;
import java.util.Scanner;
public class Count {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char key = input.nextLine().charAt(0);
countString(str, key);
}
public static void countString(String str, char searchKey) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count++;
}
System.out.println("Number of Occurrence of "
+ searchKey + " is " + count + " in string " + str);
for (int i = 0; i < count; i++) {
System.out.println(searchKey);
}
if (count > 0) {
System.out.println(count);
}
}
}
I would create a method such as the one below:
public static String stringCounter(String k) {
char[] strings = k.toCharArray();
int numStrings = strings.length;
Map<String, Integer> m = new HashMap<String, Integer>();
int counter = 0;
for(int x = 0; x < numStrings; x++) {
for(int y = 0; y < numStrings; y++) {
if(strings[x] == strings[y]) {
counter++;
}
}m.put(String.valueOf(strings[x]), counter);
counter = 0;
}
for(int x = 0; x < strings.length; x++) {
System.out.println(m.get(String.valueOf(strings[x])) + String.valueOf(strings[x]));
}
return m.toString();
}
}
Obviously as you did, I would pass a String as the argument to the stringCounter method. I would convert the String to a charArray in this scenario and I would also create a map in order to store a String as the key, and store an Integer for the number of times that individual string occurs in the character Array. The variable counter will count how many times that individual String occurs. We can then create a nested for loop. The outer loop will loop through each character in the array and the inner loop will compare it to each character in the array. If there is a match, the counter will increment. When the nested loop is finished, we can add the character to the Map along with the number of times it occurred in the loop. We can then print the results in another for loop my iterating through the map and the char array. We can print the number of times the character occurred as you mentioned doing, along with the value. We can also return the String value of the map which looks cleaner too. But you can simply make this method void if you don't want to return the map. The output should be as follows:
I tested the method in the main method by entering the String "Hello world":
System.out.println(stringCounter("Hello World"));
And here is our final output:
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
You get the number of times each character occurs in the String and you can use either the Map or print the output.
Now for your scanner. To add the Scanner to the program here is the code that you will need to add at the top of your code to prompt the user for String input:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a String: ");
String str = scan.nextLine();
System.out.println(stringCounter(str));
You have to create the Scanner Object first, adding System.in to the constructor to get input from the keyboard. You can then prompt the user with a print statement to enter a String. You can then create a String variable which will store the String by calling the "Scanner.nextLine()" method as the value. This will grab the next line of userinput from the keyboard. Now you can pass the userinput to our method and it will operate the same way. Here is what it should look like to the user:
Please enter a String:
Hello World
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}

java program to count the number of words that starts with capital letters

I want to write a program that count the number of words that starts with capital letters. It only count no. Of capital letter not word try this line
"Hi hOw are yOu"
According to my code output will be 3
But their is only 1 word that starts with capital letter that is 'Hi'...so how can I solve these problem..Please help me with this.
import java.util.*;
class Cap
{
public static void main(String m[])
{
Scanner in=new Scanner(System.in);
String s=new String();
System.out.println("Enter a line:");
s=in.nextLine();
char c;
int ct=0;
for(int i=0;i<s.length();i++)
{
c=s.charAt(i);
if(c>=65 && c<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
}
You should better use scanner.next();, which returns the token up to white space in other way a word.Now, you can check the first character of String returned by next() is in uppercase or not.
For statement This is StackOverflow you will have three tokens, This, is and StackOverflow and you can use String.charAt(0) on this String.
Moreover, you can simply use Character.isUpperCase method to check whether character is in upper case or not.
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital latter... " + count );
}
}
Currently you are counting all the capital letters that are entered.
What you want to do is split the line on space and check only for the first letter if it is capital.
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s;
System.out.println("Enter a line:");
s=in.nextLine();
int ct=0;
for(String str: s.split(" ")) {
if(str.charAt(0)>=65 && str.charAt(0)<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
You are comparing each character.Instead you can add a space at the begining of the string and check each character after space if it is in uppercase.
Scanner in = new Scanner(System. in );
String s = new String();
System.out.println("Enter a line:");
s = " " + in .nextLine().trim();
char c;
int ct = 0;
for (int i = 1; i < s.length(); i++) {
c = s.charAt(i);
if (c >= 65 && c <= 90 && s.charAt(i - 1) == 32) {
ct++;
}
}
System.out.println("total number of words start with capital letters are :" + ct);
DEMO
or better use scanner.next() as said by TAsk
Try this:
Scanner in = new Scanner(System.in);
String s = new String();
System.out.println("Enter a line:");
s = in.nextLine();
char c;
int ct = 0;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (Character.isUpperCase(c)
&& (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
ct++;
}
}
System.out
.println("total number of words start with capital letters are :"
+ ct);
First of all we check on the first position whether it is starts with capital letter or not and it is only for the string which starts with capital letter... If yes then the count will be incremented. Next condition( Which is used for string which start with blank space or any other string) will check that left position must have blank space to start new word and the character must be capital to increment the count variable...
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital letter... " + count );
}
}

Print Words In String Backwards

So I'm having a bit of trouble with my Computer Science class. I need to write some code that will take a string and print it backwards in reverse word order. He told me to find an empty space, then print from there and then keep searching....and repeat this until the end of the string. I typed my code out and all it does it print the first word 3 times. I know this will probably seem obvious to you guys.
public class Backwords
/*
* Gets words from main and prints in reverse order
*/
public static String BackwardsString(String str)
{
String str1 = (" " + str);
String answer = (" ");
int lastpos = str1.length();
for(int currpos = str.length(); currpos >= 0; currpos--) //shazam
{
if (str1.charAt(currpos) == ' ')
{
for (int p = currpos+1; p <lastpos; p++) //majicks
answer = answer + str1.charAt(p);
lastpos = currpos;
System.out.println(answer);
}
}
return answer;
}
public static void main(String [] args)
{
System.out.println("Enter a string : ");
Scanner firststr = new Scanner(System.in); //gets string input
String str = firststr.next();
System.out.println(BackwardsString(str));
}
}
Set answer back to answer = "" before the second nested for loop
for(int currpos = str.length(); currpos >= 0; currpos--) //shazam
{
if (str1.charAt(currpos) == ' ')
{
answer = "";
for (int p = currpos+1; p <lastpos; p++) //majicks
answer = answer + str1.charAt(p);
lastpos = currpos;
System.out.println(answer);
}
}
You should use StringBuilder instead of String here since there can be lot of String concatenation which may create more object in the heap.
Using StringBuilder you can do this easy way too.
Eg:
public static String BackwardsString(String str) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
return stringBuilder.reverse().toString();
}
public static void main(String[] args) {
System.out.println("Enter a string : ");
Scanner firststr = new Scanner(System.in);
String str = firststr.next();
System.out.println(BackwardsString(str));
}
try this
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string ");
String str = sc.nextLine();
String[] strArray = str.split(" ");
StringBuilder reverseString = new StringBuilder("");
for (int i = strArray.length - 1; i >= 0; i--) {
reverseString.append(strArray[i]+" ");
}
System.out.println("Reverse of string is : "+reverseString.toString());
You'd probably have an easier time splitting the string:
String[] words = str1.split(" ");
Then you'd work on each word[i] reversing it, you could break it down to a char array, or use a stringbuilder as others have suggested, up to you on what you think is appropriate for your class.

Reverse string code error

The program supposed to ask the user to enter a string then the program will reverse it and display it, but the code only return the first letter
import java.util.*;
public class ReverseString {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = scan.next();
int x = s.length();
char c = ' ';
for(int i=x-1; i>=0;i--){
c = s.charAt(i);
}
System.out.print("The reverse of String " + s + " is ");
System.out.print(c);
}
}
Output:
Enter a String: Welcome
The reverse of String Welcome is W
You're overwriting value of c in each iteration, change it to string and add to it in the loop
String c = "";
for(int i=x-1; i>=0;i--){
c += s.charAt(i);
}
Change char c = ' '; to String reverse=""; and append the character to it for each iteration.
The problem in your code is char c can hold only one character at a time.
Do like this
String reverse ="";
for(int i=s.length()-1; i>=0;i--){
reverse += s.charAt(i);
}
System.out.print(reverse);
A character is one letter; not a string.... the easiest way to do this, would be to use a StringBuilder like so -
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = scan.next();
// int x = s.length();
// char c = ' ';
// for (int i = x - 1; i >= 0; i--) {
// c = s.charAt(i);
//}
StringBuilder c = new StringBuilder(s);
c = c.reverse();
System.out.print("The reverse of String " + s + " is ");
System.out.print(c);
}
Or, if you want to use your current approach you can (by printing one character at time) like this -
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = scan.next();
System.out.print("The reverse of String " + s + " is ");
int x = s.length();
for (int i = x - 1; i >= 0; i--) {
char c = s.charAt(i);
System.out.print(c);
}
System.out.println();
}
If you want to make laugh your teacher (or maybe not) ;)
org.apache.commons.lang.StringUtils.reverse(s)
or without lib:
new StringBuffer(s).reverse().toString();
More efficient approach:
char[] strArray = s.toCharArray();
int len = strArray.length;
int max = (int)Math.ceil(len / 2.0);
char t;
for (int i = 0; i < max; ++i) {
t = strArray[i];
strArray[i] = strArray[len - i - 1];
strArray[len - i - 1] = t;
}
System.out.println(String.valueOf(strArray));

Categories

Resources