Add Something to Char Array at Specific Spot (Java) - java

I am tasked with taking a user sentence then separating it at the upper case letters as well as making those letters lower case after adding a " ".
I want to add a space add that position so that if user inputs "HappyDaysToCome" will output "Happy days to come".
Current code
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Please enter a sentence");
String sentenceString = s.nextLine();
char[] sentenceArray = sentenceString.toCharArray();
for(int i = 0; i < sentenceArray.length; i++)
{
if(i!=0 && Character.isUpperCase(sentenceArray[i]))
{
Character.toLowerCase(sentenceArray[i]);
sentenceArray.add(i, ' ');
}
}
System.out.println(sentenceArray)
s.close();
}
}

There is no add method for arrays. Arrays are not resizeable. If you indeed want to use a char[] array, you need to allocate one that is large enough, e.g. by counting the uppercase letters or simply by allocating a array that is surely large enough (twice the String length minus 1).
String input = ...
String outputString;
if (input.isEmpty()) {
outputString = "";
} else {
char[] output = new char[input.length() * 2 - 1];
output[0] = input.charAt(0);
int outputIndex = 1;
for (int i = 1; i < input.length(); i++, outputIndex++) {
char c = input.charAt(i);
if (Character.isUpperCase(c)) {
output[outputIndex++] = ' ';
output[outputIndex] = Character.toLowerCase(c);
} else {
output[outputIndex] = c;
}
}
outputString = new String(output, 0, outputIndex);
}
System.out.println(outputString);
Or better still use a StringBuilder
String input = ...
String outputString;
if (input.isEmpty()) {
outputString = "";
} else {
StringBuilder sb = new StringBuilder().append(input.charAt(0));
for (int i = 1; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isUpperCase(c)) {
sb.append(' ').append(Character.toLowerCase(c));
} else {
sb.append(c);
}
}
outputString = sb.toString();
}
System.out.println(outputString);

You're approaching this the wrong way. Just add each char back to a new string but with spaces included at the right spots. Don't worry about modifying your char array at all. Here is a slight modification of your code:
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Please enter a sentence");
String sentenceString = s.nextLine();
char[] sentenceArray = sentenceString.toCharArray();
//new string to hold the output
//starts with only the first char of the old string
string spacedString = sentenceArray[0] + "";
for(int i = 1; i < sentenceArray.length; i++)
{
if(Character.isUpperCase(sentenceArray[i]))
{
//if we find an upper case char, add a space and the lower case of that char
spacedString = spacedString + " " + Character.toLowerCase(sentenceArray[i]);
}else {
//otherwise just add the char itself
spacedString = spacedString + sentenceArray[i];
}
}
System.out.println(spacedString)
s.close();
}
If you want to optimize performance, you can use a StringBuilder object. However, for spacing out a single sentence, performance isn't going to make any real difference at all. If performance does matter to you, read more on StringBuilder here: https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

We basically want to tokenize the input string on uppercase letters. This can be done using the regular expression [A-Z][^A-Z]* (i.e., one uppercase, followed by zero or more "not" uppercase). The String class has a built-in split() method that takes a regular expression. Unfortunately, you also want to keep the delimiter (which is the uppercase letter), so that slightly complicates matters, but it can still be done using Pattern and Matcher to put the matched delimiter back into the string:
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.List;
import java.util.ArrayList;
public class Foo {
public static void main(String[] args) {
String text = "ThisIsATest1234ABC";
String regex = "\\p{javaUpperCase}[^\\p{javaUpperCase}]*";
Matcher matcher = Pattern.compile(regex).matcher(text);
StringBuffer buf = new StringBuffer();
List<String> result = new ArrayList<String>();
while(matcher.find()){
matcher.appendReplacement(buf, matcher.group());
result.add(buf.toString());
buf.setLength(0);
}
matcher.appendTail(buf);
result.add(buf.toString());
String resultString = "";
for(String s: result) { resultString += s + " "; }
System.out.println("Final: \"" + resultString.trim() + "\"");
}
}
Output:
Final: "This Is A Test1234 A B C"

Related

How to insert a char before each char in a string, but not before 'space' in Java?

This is what I got. It works for now, but if I type, for example, "I like bananas", I get 'pIp ppipkpep pbpapnpapnpaps', while I'm aiming to get 'pI pLpipkpe pbpapnpapnpaps.
Every solution I tried came down to using an 'if statement', trying to check if the character at said position in the original 'encText'is equal to ' ', and if so, making it equal to ' ' as well in the newText array before checking if the position required an 'p' or the char from the original array.. However, everytime I tried that, I'd get an array out of bounds exception.
static void pEncrypt() {
System.out.println("Adding P");
Scanner in = new Scanner(System.in);
String encText = in.nextLine();
int k = encText.length();
char[] charsEncText = encText.toCharArray();
char[] newText = new char[2*k];
int j = 1;
for (int i = 0; i < (k*2); i++) {
if (i%2 == 0) {
newText[i] = 'p';
} else {
newText[i] = charsEncText[i-j];
j++;
}
}
System.out.println(newText);
}
A simpler solution is to use replaceAll with a positive lookahead.
String str = "I like bananas";
String res = str.replaceAll("(?=[^ ])", "p");
System.out.println(res); // "pI plpipkpe pbpapnpapnpaps"
Demo
You can try this way.
static void pEncrypt() {
System.out.println("Adding P");
Scanner in = new Scanner(System.in);
String encText = in.nextLine();
int k = encText.length();
char[] charsEncText = encText.toCharArray();
char[] newText = new char[2*k];
int j=0;
for(int i=0;i<k;i++)
{
if(charsEncText[i]==' ')
{
newText[j]=charsEncText[i];
j++;
}
else{
newText[j]='p';
newText[j+1]=charsEncText[i];
j=j+2;
}
}
System.out.println(newText);
}
Assuming one does not need a char[], I would just concatenate to a String. Something like:
public static String pEncrypt(String org)
{
String ret = "";
for (int i = 0; i < org.length(); ++i) {
char ch = org.charAt(i);
if (ch != ' ') {
ret += "p" + ch;
}
else {
ret += ' ';
}
}
return ret;
}
Also, to make things a bit easier, it is generally a good idea to separate the I/O (i.e., the Scanner and the println) from the processing. That way, one can write test cases rather than attempting to keep inputting the information.
Sample Output:
helloworld ==> phpeplplpopwpoprplpd
I like bananas ==> pI plpipkpe pbpapnpapnpaps

How do I replace more than one type of Character in Java String

newbie here. Any help with this problem would be appreciated:
You are given a String variable called data that contain letters and spaces only. Write the Java class to print a modified version of the String where all lowercase letters are replaced by ? and all whitespaces are replaced by +. An example is shown below: I Like Java becomes I+L???+J???.
What I have so far:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
for (int i = 0; i < data.length(); i++) {
if (Character.isWhitespace(data.charAt(i))) {
data.replace("", "+");
if (Character.isLowerCase(data.charAt(i))) {
data.replace(i, i++, ); //not sure what to include here
}
} else {
System.out.print(data);
}
}
}
any suggestions would be appreciated.
You can do it in two steps by chaining String#replaceAll. In the first step, replace the regex, [a-z], with ?. The regex, [a-z] means a character from a to z.
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
str = str.replaceAll("[a-z]", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+L???+J???
Alternatively, you can use a StringBuilder to build the desired string. Instead of using a StringBuilder variable, you can use String variable but I recommend you use StringBuilder for such cases. The logic of building the desired string is simple:
Loop through all characters of the string and check if the character is a lowercase letter. If yes, append ? to the StringBuilder instance else if the character is whitespace, append + to the StringBuilder instance else append the character to the StringBuilder instance as it is.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (Character.isLowerCase(ch)) {
sb.append('?');
} else if (Character.isWhitespace(ch)) {
sb.append('+');
} else {
sb.append(ch);
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+L???+J???
If the requirement states:
The first character of each word is a letter (uppercase or lowercase) which needs to be left as it is.
Second character onwards can be any word character which needs to be replaced with ?.
All whitespace characters of the string need to be replaced with +.
you can do it as follows:
Like the earlier solution, chain String#replaceAll for two steps. In the first step, replace the regex, (?<=\p{L})\w, with ?. The regex, (?<=\p{L})\w means:
\w specifies a word character.
(?<=\p{L}) specifies a positive lookbeghind for a letter i.e. \p{L}.
In the second step, simply replace one or more whitespace characters i.e. \s+ with +.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
str = str.replaceAll("(?<=\\p{L})\\w", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+l???+J???
Alternatively, again like the earlier solution you can use a StringBuilder to build the desired string. Loop through all characters of the string and check if the character is a letter. If yes, append it to the StringBuilder instance and then loop through the remaining characters until all characters are exhausted or a space character is encountered. If a whitespace character is encountered, append + to the StringBuilder instance else append ? to it.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i++);
if (Character.isLetter(ch)) {
sb.append(ch);
while (i < len && !Character.isWhitespace(ch = str.charAt(i))) {
sb.append('?');
i++;
}
if (Character.isWhitespace(ch)) {
sb.append('+');
}
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+l???+J???
package com.company;
import java.util.*;
public class dat {
public static void main(String[] args) {
System.out.println("enter the string:");
Scanner ss = new Scanner(System.in);
String data = ss.nextLine();
for (int i = 0; i < data.length(); i++) {
char ch = data.charAt(i);
if (Character.isWhitespace(ch))
System.out.print("+");
else if (Character.isLowerCase(ch))
System.out.print("?");
else
System.out.print(ch);
}
}
}
enter the string:
i Love YouU
?+L???+Y??U
Firstly, you are trying to make changes to String object which is immutable. Simple way to achieve what you want is convert string to character array and loop over array items:
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
char[] dataArray = data.toCharArray();
for (int i = 0; i < dataArray.length; i++) {
if (Character.isWhitespace(dataArray[i])) {
dataArray[i] = '+';
} else if (Character.isLowerCase(dataArray[i])) {
dataArray[i] = '?';
}
}
System.out.print(dataArray);
See the below code and figure out what's wrong in your code. To include multiple regex put the char within square brackets:
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String data = input.nextLine();
String one = data.replaceAll(" ", "+");
String two = one.replaceAll("[a-z]", "?");
System.out.println(two);
}
}
You can use String.codePoints method to get a stream over int values of characters of this string, and process them:
private static String replaceCharacters(String str) {
return str.codePoints()
.map(ch -> {
if (Character.isLowerCase(ch))
return '?';
if (Character.isWhitespace(ch))
return '+';
return ch;
})
.mapToObj(Character::toString)
.collect(Collectors.joining());
}
public static void main(String[] args) {
System.out.println(replaceCharacters("Lorem ipsum")); // L????+?????
System.out.println(replaceCharacters("I Like Java")); // I+L???+J???
}
See also: Replace non ASCII character from string

Generate palindrome words

So, I have this code which generates palindrome words in a special manner.
1> it joins the word by its reverse(excluding last character).
2> the words which end with repeated alphabets, for example ABB becomes ABBA and not ABBBA and XAZZZ becomes XAZZZAX.
I am already done with the first part. I have just tried second one by extracting last two characters, because to be honest, I don't know how should I do it.
import java.io.*;
class ISC_Q3_2019
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ISC_Q3_2019 ob = new ISC_Q3_2019();
System.out.println("Enter your sentence");
String s = br.readLine();
s=s.toUpperCase();
String words[] = s.split(" ");
int l=words.length;
char ch1=s.charAt(s.length()-1);
String ans=" ", copy=" ", p=" ";
if(ch1=='.'||ch1=='!'||ch1=='?')
{
for(int i=0;i<l;i++)
{
if(ob.isPalindrome(words[i])==true)
{
ans=ans+words[i];
}
else
{
copy=words[i];
words[i]=ob.Reverse(words[i]);
p=copy.concat(words[i]);
ans=ans+p;
}
}
System.out.println("OUTPUT:" +ans.trim());
}
else
System.out.println("Invalid Input!");
}
boolean isPalindrome(String s)
{
s=s.toUpperCase();
int l=s.length();
char ch;
String rev=" ", copy=" ";
copy=s;
for(int i=l-1;i>=0;i--)
{
ch=s.charAt(i);
rev=rev+ch;
}
if(rev.equals(copy))
return true;
else
return false;
}
String Reverse(String s)
{
s=s.toUpperCase();
int l=s.length();
char ch, ch1, ch2;
String r=" ";
for(int i=l-2;i>=0;i--)
{
ch=s.charAt(i);
ch1=s.charAt(l-1);
ch2=s.charAt(l-2);
if(ch1==ch2)
r=r+ch;
else
r=r+ch;
}
return r;
}
}
OUTPUT:
Enter your sentence
The abb is flying.
**OUTPUT:**THE HTABB BAIS IFLYING. GNIYLF
And another part I am concerned is the unmatched spaces.
Here you go
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Palindrome {
public static void main(String... args) {
// Request for input
Scanner reader = new Scanner(System.in);
System.out.println("Enter your sentence...");
// Read the user input
String sentence = reader.nextLine();
// Split the sentence (into tokens) at spaces and special characters using regex
// Keep the special characters where they are and form a List with the split words
List<String> tokens = Arrays.asList(sentence.split("((?<=[\\?,\\. ])|(?=[\\?,\\. ]))"));
// For every token/word, form the palindrome of that and then join them back
String result = tokens.stream().map(s -> formPalindrome(s)).collect(Collectors.joining());
// This is the final result
System.out.println("result: " + result);
reader.close();
}
private static String formPalindrome(String str) {
// Reverse the String
String reversed = new StringBuilder(str).reverse().toString();
// String length
int strLen = reversed.length();
// Compare each character of reversed string with last character of the string until they are different
// When they are different concat the substring with original string
for (int i = 0; i < strLen; i++) {
if (reversed.charAt(i) != str.charAt(strLen - 1)) {
return str + reversed.substring(i);
}
}
return str;
}
}
Here is an idea* that you can build on to get the desired result:
Check the original Strings characters in reverse and count how
many occurences there are
Create a new String from the start of the original String, up
to the end less the count of occurences
Reverse that new String
Concatenate the original String with the new String
So a quickly thrown together example:
int count = 0;
for (int i = s.length() - 1; i > 0; i--) {
if (s.charAt(i) == s.charAt(i - 1)) {
count++;
} else {
break;
}
}
StringBuilder sb = new StringBuilder(s.substring(0, s.length() - 1 - count)).reverse();
System.out.println(s + sb.toString());
Which would give "ABBA" for "ABB" and "XAZZAX" for "XAZZZ".
* It's only an idea and there are probably edge cases etc that aren't catered for but it's merely to give the OP an idea of how to approach it

how to capitalize first letter after period in each sentence using java?

I'm currently learning on how to manipulate strings and i think it'll take awhile for me to get used to it. I wanted to know how to capitalize a letter after a period in each sentence.
The output is like this:
Enter sentences: i am happy. this is genius.
Capitalized: I am happy. This is genius.
I have tried creating my own code but its not working, feel free to correct and change it. Here is my code:
package Test;
import java.util.Scanner;
public class TestMain {
public static void main(String[]args) {
String sentence = getSentence();
int position = sentence.indexOf(".");
while (position != -1) {
position = sentence.indexOf(".", position + 1);
sentence = Character.toUpperCase(sentence.charAt(position)) + sentence.substring(position + 1);
System.out.println("Capitalized: " + sentence);
}
}
public static String getSentence() {
Scanner hold = new Scanner(System.in);
String sent;
System.out.print("Enter sentences:");
sent = hold.nextLine();
return sent;
}
}
The tricky part is how am i gonna capitalize a letter after the period(".")? I don't have a lot of string manipulation knowledge so I'm really stuck in this area.
Try this:
package Test;
import java.util.Scanner;
public class TestMain {
public static void main(String[]args){
String sentence = getSentence();
StringBuilder result = new StringBuilder(sentence.length());
//First one is capital!
boolean capitalize = true;
//Go through all the characters in the sentence.
for(int i = 0; i < sentence.length(); i++) {
//Get current char
char c = sentence.charAt(i);
//If it's period then set next one to capital
if(c == '.') {
capitalize = true;
}
//If it's alphabetic character...
else if(capitalize && Character.isAlphabetic(c)) {
//...we turn it to uppercase
c = Character.toUpperCase(c);
//Don't capitalize next characters
capitalize = false;
}
//Accumulate in result
result.append(c);
}
System.out.println(result);
}
public static String getSentence(){
Scanner hold = new Scanner(System.in);
String sent;
System.out.print("Enter sentences:");
sent = hold.nextLine();
return sent;
}
}
What this is doing it advancing sequentially through all of the characters in the string and keeping state of when the next character needs to be capitalized.
Follow the comments for a deeper exaplanations.
You could implement a state machine:
It starts in the capitalize state, as each character is read it emits it and then decides what state to go to next.
As there are just two states, the state can be stored in a boolean.
public static String capitalizeSentence(String sentence) {
StringBuilder result = new StringBuilder();
boolean capitalize = true; //state
for(char c : sentence.toCharArray()) {
if (capitalize) {
//this is the capitalize state
result.append(Character.toUpperCase(c));
if (!Character.isWhitespace(c) && c != '.') {
capitalize = false; //change state
}
} else {
//this is the don't capitalize state
result.append(c);
if (c == '.') {
capitalize = true; //change state
}
}
}
return result.toString();
}
Here is solution with regular expressions:
public static void main(String[]args) {
String sentence = getSentence();
Pattern pattern = Pattern.compile("^\\W*([a-zA-Z])|\\.\\W*([a-zA-Z])");
Matcher matcher = pattern.matcher(sentence);
StringBuffer stringBuffer = new StringBuffer("Capitalized: ");
while (matcher.find()) {
matcher.appendReplacement(stringBuffer, matcher.group(0).toUpperCase());
}
matcher.appendTail(stringBuffer);
System.out.println(stringBuffer.toString());
}
Seems like your prof is repeating his assignments. This has already been asked:
Capitalize first word of a sentence in a string with multiple sentences
Use a pre-existing lib:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#capitalize(java.lang.String,%20char...)
and guava
public static void main(String[] args) {
String sentences = "i am happy. this is genius.";
Iterable<String> strings = Splitter.on('.').split(sentences);
List<String> capStrings = FluentIterable.from(strings)
.transform(new Function<String, String>()
{
#Override
public String apply(String input){
return WordUtils.capitalize(input);
}
}).toList();
System.out.println(Joiner.on('.').join(capStrings));
}
Just use
org.apache.commons.lang3.text.WordUtils.capitalizeFully(sentence);
You can use below code to capitalize first letter after period in
each sentence.
String input = "i am happy. this is genius.";
String arr[] = input.split("\\.");
for (int i = 0; i < arr.length; i++) {
System.out.print(Character.toUpperCase(arr[i].trim().
charAt(0)) + arr[i].trim().substring(1) + ". ");
}
I'd go for regex as it is fast to use:
Split your string by ".":
String[] split = input.split("\\.");
Then capitalize the first letter of the resulting substrings and reunite to result string. (Be careful for spaces between periods and letters, maybe split by "\. "):
String result = "";
for (int i=0; i < split.length; i++) {
result += Character.toUpperCase(split[i].trim());
}
System.out.println(result);
Should do it.
The correct method to do it with core java using regex will be
String sentence = "i am happy. this is genius.";
Pattern pattern = Pattern.compile("[^\\.]*\\.\\s*");
Matcher matcher = pattern.matcher(sentence);
String capitalized = "", match;
while(matcher.find()){
match = matcher.group();
capitalized += Character.toUpperCase(match.charAt(0)) + match.substring(1);
}
System.out.println(capitalized);
Try this:
1. Capitalize the first letter.
2. If the character is '.' set the flag true so that you can capitalize the next character.
public static String capitalizeSentence(String str)
{
if(str.length()>0)
{
char arr[] = str.toCharArray();
boolean flag = true;
for (int i = 0; i < str.length(); i++)
{
if (flag)
{
if (arr[i] >= 97 && arr[i] <= 122)
{
arr[i] = (char) (arr[i] - 32);
flag = false;
}
} else
{
if (arr[i] == '.')
flag = true;
}
}
return new String(arr);
}
return str;
}

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

Alternately display any text that is typed in the textbox
// in either Capital or lowercase depending on the original
// letter changed. For example: CoMpUtEr will convert to
// cOmPuTeR and vice versa.
Switch.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e )
String characters = (SecondTextField.getText()); //String to read the user input
int length = characters.length(); //change the string characters to length
for(int i = 0; i < length; i++) //to check the characters of string..
{
char character = characters.charAt(i);
if(Character.isUpperCase(character))
{
SecondTextField.setText("" + characters.toLowerCase());
}
else if(Character.isLowerCase(character))
{
SecondTextField.setText("" + characters.toUpperCase()); //problem is here, how can i track the character which i already change above, means lowerCase**
}
}}
});
setText is changing the text content to exactly what you give it, not appending it.
Convert the String from the field first, then apply it directly...
String value = "This Is A Test";
StringBuilder sb = new StringBuilder(value);
for (int index = 0; index < sb.length(); index++) {
char c = sb.charAt(index);
if (Character.isLowerCase(c)) {
sb.setCharAt(index, Character.toUpperCase(c));
} else {
sb.setCharAt(index, Character.toLowerCase(c));
}
}
SecondTextField.setText(sb.toString());
You don't have to track whether you've already changed the character from upper to lower. Your code is already doing that since it's basically:
1 for each character x:
2 if x is uppercase:
3 convert x to lowercase
4 else:
5 if x is lowercase:
6 convert x to uppercase.
The fact that you have that else in there (on line 4) means that a character that was initially uppercase will never be checked in the second if statement (on line 5).
Example, start with A. Because that's uppercase, it will be converted to lowercase on line
3 and then you'll go back up to line 1 for the next character.
If you start with z, the if on line 2 will send you directly to line 5 where it will be converted to uppercase. Anything that's neither upper nor lowercase will fail both if statements and therefore remain untouched.
You can use StringUtils.swapCase() from org.apache.commons
This is a better method :-
void main()throws IOException
{
System.out.println("Enter sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
String sentence = "";
for(int i=0;i<str.length();i++)
{
if(Character.isUpperCase(str.charAt(i))==true)
{
char ch2= (char)(str.charAt(i)+32);
sentence = sentence + ch2;
}
else if(Character.isLowerCase(str.charAt(i))==true)
{
char ch2= (char)(str.charAt(i)-32);
sentence = sentence + ch2;
}
else
sentence= sentence + str.charAt(i);
}
System.out.println(sentence);
}
The problem is that you are trying to set the value of SecondTextField after checking every single character in the original string. You should do the conversion "on the side", one character at a time, and only then set the result into the SecondTextField.
As you go through the original string, start composing the output from an empty string. Keep appending the character in the opposite case until you run out of characters. Once the output is ready, set it into SecondTextField.
You can make an output a String, set it to an empty string "", and append characters to it as you go. This will work, but that is an inefficient approach. A better approach would be using a StringBuilder class, which lets you change the string without throwing away the whole thing.
String name = "Vikash";
String upperCase = name.toUpperCase();
String lowerCase = name.toLowerCase();
This is a better approach without using any String function.
public static String ReverseCases(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char temp;
if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
temp = (char)(str.charAt(i) - 32);
}
else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){
temp = (char)(str.charAt(i) + 32);
}
else {
temp = str.charAt(i);
}
sb.append(temp);
}
return sb.toString();
}
Here you are some other version:
public class Palindrom {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word to check: ");
String checkWord = sc.nextLine();
System.out.println(isPalindrome(checkWord));
sc.close();
}
public static boolean isPalindrome(String str) {
StringBuilder secondSB = new StringBuilder();
StringBuilder sb = new StringBuilder();
sb.append(str);
for(int i = 0; i<sb.length();i++){
char c = sb.charAt(i);
if(Character.isUpperCase(c)){
sb.setCharAt(i, Character.toLowerCase(c));
}
}
secondSB.append(sb);
return sb.toString().equals(secondSB.reverse().toString());
}
}
StringBuilder b = new StringBuilder();
Scanner s = new Scanner(System.in);
String n = s.nextLine();
for(int i = 0; i < n.length(); i++) {
char c = n.charAt(i);
if(Character.isLowerCase(c) == true) {
b.append(String.valueOf(c).toUpperCase());
}
else {
b.append(String.valueOf(c).toLowerCase());
}
}
System.out.println(b);
Methods description:
*toLowerCase()* Returns a new string with all characters converted to lowercase.
*toUpperCase()* Returns a new string with all characters converted to uppercase.
For example:
"Welcome".toLowerCase() returns a new string, welcome
"Welcome".toUpperCase() returns a new string, WELCOME
If you look at characters a-z, you'll see that all of them have the 6th bit is set to 1. Where in A-Z 6th bit is not set.
A = 1000001 a = 1100001
B = 1000010 b = 1100010
C = 1000011 c = 1100011
D = 1000100 d = 1100100
...
Z = 1011010 z = 1111010
So all we need to do is to iterate through each character from a given string and then do XOR(^) with 32. In this way, the 6th bit can swap.
Look at the below code for simply changing the string case without using any if-else conditions.
public final class ChangeStringCase {
public static void main(String[] args) {
String str = "Hello World";
for (int i = 0; i < str.length(); i++) {
char ans = (char)(str.charAt(i) ^ 32);
System.out.print(ans); // Final Output: hELLO wORLD
}
}
}
Time Complexity: O(N) where N = Length of the string.
Space Complexity: O(1)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String satr=scanner.nextLine();
String newString = "";
for (int i = 0; i < satr.length(); i++) {
if (Character.isUpperCase(satr.charAt(i))) {
newString+=Character.toLowerCase(satr.charAt(i));
}else newString += Character.toUpperCase(satr.charAt(i));
}
System.out.println(newString);
}
public class Toggle {
public static String toggle(String s) {
char[] ch = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
char charat = ch[i];
if (Character.isUpperCase(charat)) {
charat = Character.toLowerCase(charat);
} else
charat = Character.toUpperCase(charat);
System.out.print(charat);
}
return s;
}
public static void main(String[] args) {
toggle("DivYa");
}
}
import java.util.Scanner;
class TestClass {
public static void main(String args[]) throws Exception {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (Character.isUpperCase(ch[i])) {
ch[i] = Character.toLowerCase(ch[i]);
} else {
ch[i] = Character.toUpperCase(ch[i]);
}
}
System.out.println(ch);
}
}
//This is to convert a letter from upper case to lower case
import java.util.Scanner;
public class ChangeCase {
public static void main(String[]args) {
String input;
Scanner sc= new Scanner(System.in);
System.out.println("Enter Letter from upper case");
input=sc.next();
String result;
result= input.toLowerCase();
System.out.println(result);
}
}
String str1,str2;
Scanner S=new Scanner(System.in);
str1=S.nextLine();
System.out.println(str1);
str2=S.nextLine();
str1=str1.concat(str2);
System.out.println(str1.toLowerCase());

Categories