Removing negative sign from a string - java

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.

Related

String of only even numbers and only odd numbers

I know there are already questions asking something similar to my question, but despite reading those, they don't quite do what I want.
I am creating a code that takes a users input of a number between 0-100 (inclusive). Whatever the number, it will print all the numbers leading up to that number and that number
EX: user input = 25
output = 012345678910111213141516171819202122232425
I have that part working. Now I am supposed to use that string and create two new strings, one for only the odd and the other one for the even numbers.
EX: user input = 25
output: odd numbers: 135791113151719212325 & even numbers = 024681012141618202224
Here is my code so far:
import java.util.Scanner;
public class OddAndEven{
public String quantityToString() {
Scanner number = new Scanner(System.in);
int n = number.nextInt();
String allNums = "";
if ((n >= 0) && (n <= 100)) {
for (int i = 0;i <= n; ++i)
allNums = allNums + i;
return allNums;
}
else {
return "";
}
}
public void oddAndEvenNumbers(int num) {//Start of second method
String allNums = ""; //String that quantityToString returns
String odd = "";
String even = "";
if ((num >= 0) && (num < 10)) { //Looks at only single digit numbers
for (int i = 0; i <= allNums.length(); i++) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) { //trying to get the allNums string to be broken into individual numbers to evaluate
even = even + allNums.charAt(i); //adding the even numbers of the string
}
else {
odd = odd + allNums.charAt(i);
}
}
}
else { //supposed to handle numbers with double digits
for (int i = 10; i <= allNums.length(); i = i + 2) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) {
even = even + allNums.charAt(i);
}
else {
odd = odd + allNums.charAt(i);
}
}
}
System.out.println("Odd Numbers: " + odd);
System.out.println("Even Numbers: " + even);
}
public static void main(String[] args) {
System.out.println(new OddAndEven().quantityToString());
//System.out.println(new OddAndEven().oddAndEvenNumbers(allNums));
//Testing
OddAndEven obj = new OddAndEven();
System.out.println("Testing n = 5");
obj.oddAndEvenNumbers(5);
System.out.println("Testing n = 99");
obj.oddAndEvenNumbers(99);
I know my problem is at the part when its supposed to take the string apart and evaluate the individual numbers, but I don't know what to do. (I've also tried substring() & trim()) Also I have not learned how to use arrays yet, so that is why I did not try to use an array.
I think you can make it that way:
int x = 20;
StringBuilder evenNumberStringBuilder = new StringBuilder();
StringBuilder oddNumberStringBuilder = new StringBuilder();
for(int i =0 ; i<x+1; i++){
if(i % 2 == 0)evenNumberStringBuilder.append(i);
else oddNumberStringBuilder.append(i);
}
System.out.println(evenNumberStringBuilder);
System.out.println(oddNumberStringBuilder);
Output:
02468101214161820
135791113151719
you are already taking the input as integer, so don't work with strings. I recommend that to use this loop;
Scanner number = new Scanner(System.in);
System.out.print("Even Numbers: ");
for (int i = 0; i <= number; i=i+2) {
System.out.print(i);
}
System.out.println("");
System.out.print("Odd Numbers: ");
for (int i = 1; i <= number; i=i+2) {
System.out.print(i);
}
You can simply evaluate numbers while storing them in an allnumbers string, here's a functioning code:
int x = 23; //user input
String s=""; //contains all numbers from 0 to userinput
String odd =""; //contains all odd numbers from 0 to userinput
String even = ""; //contains all even numbers from 0 to userinput
for(int i = 0 ; i< x+1 ; i++){
s += i;
if(i%2==0) //if i is an even number
even += i;
else //if i is an odd number
odd += i;
}
System.out.println(s); //displaying all numbers from 0 to user input
System.out.println(odd); //displaying odd numbers from 0 to user input
System.out.println(even); //displaying even numbers from 0 to user input

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}

How to index characters of string backwards in Java?

I'm trying to make a program that checks for palindromes(words spelt the same forwards and backwards). I want to eventually compare the first char with the last char and the second char with the second to last char. I don't know what to put in the 'endingChar' string to make it check for that. Thanks.
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
String userPhrase;
Scanner sc = new Scanner(System. in );
System.out.println("Check for palindrome:");
userPhrase = sc.nextLine();
for (int i = 0; i < userPhrase.length(); i++) {
String currentChar = userPhrase.substring(i, i + 1);
String endingChar = userPhrase.substring();
System.out.println(currentChar);
System.out.println(endingChar);
// if (userPhrase.indexOf(currentChar).equalsIgnoreCase(userPhrase.indexOf()))
}
}
}
The simplest way to check for a palindrome would be to utilize StringBuilder.reverse():
boolean isPalindrome = userPhrase.equals(
new StringBuilder(userPhrase).reverse().toString());
System.out.printf("[%s] is a palindrome? %b", userPhrase, isPalindrome);
*Taken from Here, don't give me credit.
Here is some code for checking for a palindrome for integers. You could apply the logic to your code to make it work for strings as well:
// numbers to check
int numbers[] = new int[]{ 252, 54, 99, 1233, 66, 9876 };
// loop through the given numbers
for (int i = 0; i < numbers.length; i++) {
int numberToCheck = numbers[i];
int numberInReverse = 0;
int temp = 0;
// a number is a palindrome if the number is equal to it's reversed number
// reverse the number
while (numberToCheck > 0) {
temp = numberToCheck % 10;
numberToCheck = numberToCheck / 10;
numberInReverse = numberInReverse * 10 + temp;
}
if (numbers[i] == numberInReverse) {
System.out.println(numbers[i] + " is a palindrome");
}
else {
System.out.println(numbers[i] + " is NOT a palindrome");
}
You could rather use this
for(int i=0;;i++)
{
if(i>=userPhrase.length-i)
break;
if(userPhrase.charAt(i)==userPhrase.charAt(userPhrase.length-i))
{
continue;
}
System.out.println("Not matched");
}

Inserting dashes between two odd numbers

folks. In my program I take a user input of numbers of a String type and put dashes between two odd numbers. For example:
Input = 99946 Output = 9-9-946
Input = 56730 Output = 567-30
But in my code, if I, for example, write 9933444 then the ouput that I'm getting is: 9-9-9-3-3-3-344444. It correctly separates the odd numbers by dashes but also adds extra numbers. What could be causing this bug ?
import java.util.Arrays;
import java.util.Scanner;
public class DashInsert {
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Enter the numbers: ");
String myString = kbd.nextLine();
char[] numbers = myString.toCharArray();
String result = "";
for(int i = 1; i < numbers.length; i++)
{
int value1 = Character.getNumericValue(numbers[i]);
int value2 = Character.getNumericValue(numbers[i-1]);
if(value1 % 2 != 0 && value2 % 2 != 0)
{
result += numbers[i-1] + "-" + numbers[i] + "-";
}
else
result += numbers[i-1] + "" + numbers[i];
}
System.out.println(result);
}
}
There is a trivial one-line solution:
str = str.replaceAll("(?<=[13579])(?=[13579])", "-");
This works by matching between odd numbers and replacing the (zero-width) match with a dash. The regex is a look behind and a look ahead.
It can be done without look arounds by capturing the odd digits and putting them back using a back reference:
str = str.replaceAll("([13579])([13579])", "$1-$2");
Both solutions achieve the same result.
The code can be simplified a bit (as well as solve the "double char" bug):
String str = "9933444";
char[] numbers = str.toCharArray();
String result = "";
for(int i = 1; i < numbers.length; i++)
{
int value1 = Character.getNumericValue(numbers[i-1]);
int value2 = Character.getNumericValue(numbers[i]);
result += value1;
if(value1 % 2 != 0 && value2 % 2 != 0) {
result += "-";
}
}
result += numbers[numbers.length - 1];
System.out.println(result);
OUTPUT
9-9-3-3444
The reason for the "double char" bug is that every loop prints both the items on the places i-1 and i. which means that i will be printed again on the next loop (where it will become i-1).
In case you're using Java 8 - you can use a Stream do something that looks more like what you were originally trying to do:
public static void main(String[] args){
String str = "9933444";
List<String> lst = Arrays.asList(str.split(""));
String res = lst.stream().reduce((a,b) -> {
if (isOdd(a) && isOdd(b)) {
return a + "-" + b;
}
else {
return a + b;
}
}).get();
System.out.println(res);
}
// grep the last digit from the string and check if it's odd/even
public static boolean isOdd(String x) {
if (x.length() > 1) {
if (x.substring(x.length()-1).equals("-")) {
x = x.substring(x.length()-3, x.length()-2);
}
else {
x = x.substring(x.length() - 1);
}
}
return Integer.parseInt(x) % 2 == 1;
}
OUTPUT
9-9-3-3444
The bug is caused by the fact that, even though you are looping through your list of numbers one at a time, you write out two numbers with each loop iteration. Logically, this design will always yield repeated numbers.
Either change your loop to iterate by twos, or print a single number in each loop iteration.
Don't bother concatenating two odd numbers with the "-" in between them, during the evaluation, just add the "-" after the number that you're checking in each iteration.
public static void main(String[] args) throws Exception {
Scanner kbd = new Scanner(System.in);
System.out.println("Enter the numbers: ");
String myString = kbd.nextLine();
char[] numbers = myString.toCharArray();
String result = "";
for(int i = 0; i < numbers.length; i++) {
int value1 = Character.getNumericValue(numbers[i]);
int value2 = i + 1 < numbers.length
? Character.getNumericValue(numbers[i + 1])
: 0;
if(value1 % 2 != 0 && value2 % 2 != 0) {
result += numbers[i] + "-";
} else {
result += numbers[i];
}
}
System.out.println(result);
}
Results:
Input: 99946 Output: 9-9-946
Input: 56730 Output: 567-30
Input: 9933444 Output: 9-9-3-3444

Finding all uppercase letters of a string in 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));
}
}
}
}

Categories

Resources