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.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 months ago.
Improve this question
This a program to enter a sentence and print the longest word using substring()
Here, I have used the 1st loop to extract each word from the sentence and find the length of the longest word.
In the 2nd Loop, its purpose is it to extract and print the word that matches the length which was found out in the 1st loop and stored in the "longestLength" variable.
I am getting an error when i compile the following code:
import java.util.*;
public class Program {
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() > longestLength)
longestLength = st.length();
i1 = i;
}
}
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() == longestLength) {
System.out.println("Longest Word : " + st);
break;
}
i1=i;
}
}
}
}
Here you don't need to use for loops for just finding the longest word.
Just remove the for loops and add the following lines below that.
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
String longest = Arrays.stream(s.split(" ")).max(Comparator.comparingInt(String::length)).orElse(null);
System.out.println(longest);
YOUR FINAL CODE WILL BE:
import java.util.*;
public class Program {
public static void main(String[] args) {
String s;
int longestLength = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
String longest = Arrays.stream(s.split(" ")).max(Comparator.comparingInt(String::length)).orElse(null);
System.out.println(longest);
}
}
It will print the longest word. Hope it will be helpful to you.
There is an alternate easy method to split sentence using delimter using String.spilt(delimiter) funciton.
Below code is an working example for your task
public class Test {
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
String maxString = "";
for(String string : s.split(" ")){
maxString = maxString.length() > string.length() ? maxString : string;
}
System.out.println("The max lengthed string is : "+maxString);
}
}
Your issue is due to i1 has not be resetted to 0 hence the old loop value if i1 is there hence the issue
The solution is given below:
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() > longestLength)
longestLength = st.length();
i1 = i;
}
}
i1=0;
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() == longestLength) {
System.out.println("Longest Word : " + st);
break;
}
i1=i;
}
}
}
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}
I want a java code to encrypt a given string using 2 main strings like below
s1 = "qwertyuiopasdfghjklzxcvbnm";
s2 = "mnbvcxzasdfghjklpoiuytrewq";
If our input string is "mnb", then it is compared with s2 and the same index in s1 is added 3 then output will be "rty" but I am not getting proper output.
Can any one help me to solve this problem?
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input,out = "";
System.out.println("enter input string");
input = sc.nextLine();
for(int i=0;i<s2.length();i++){
if(input.charAt(i)==s2.charAt(i)){
out+=s1.charAt(i+3);
}
System.out.println(out);
}
sc.close();
}
You almost had the solution! The problem is when you input one of the last 3 characters of s2 you'll have to use the modulo operator (when the position gets larger than 25 you will reach the end of the string and have to start searching at the beginning!)
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input,out = "";
System.out.println("enter input string");
input = sc.nextLine();
for (int i = 0; i < input.length(); i++) {
int position = s2.indexOf(input.charAt(i));
position = (position + 3) % 26;
out = out + s1.charAt(position);
}
sc.close();
}
In order to avoid wrong user input you should check the position if it's -1 (if the character is not found in s2) and handle that case properly (exception/outprint + break in the loop)
You need an extra loop to check which character matches from s2 string.Other than that,you will have to use modulo operator to avoid ArrayIndexOutOfBound.
Try this
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input, out = "";
System.out.println("enter input string");
input = sc.nextLine();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
if (input.charAt(i) == s2.charAt(j)) {
out += s1.charAt((j + 3)%26);
}
}
}
System.out.println(out);
sc.close();
}
UPDATE
As pointed in comment by #ParkerHalo,to handle ArrayIndexOutOfBound,you can use modulo operator like this
out += s1.charAt((j + 3)%26);
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));
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));
}
}
}
}