Generate palindrome words - java

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

Related

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

Using Recursion to Reverse a String

I am trying to reverse a String word by word using recursion. (Ex: "Hello my friend" is reversed to "friend my Hello") This is the code I have attempted to write for this method. I have tried multiple similar variations but the output is only ever the first or last word of the String. I believe the part that is "broken" is the first if statement, but I am not quite sure.
public static String reverse (String words) {
Scanner sc = new Scanner(words);
String backwards = "";
if (sc.hasNext()) {
String currentWord = sc.next();
reverse(sc.nextLine());
backwards = backwards + " " + currentWord;
} //end if
else {
backwards = words;
} //end else
return backwards;
}
I am aware that a few similar questions exist, but their answers have not seemed to help me understand my mistake(s).
Thanks!
Instead of using a Scanner, you can make use of an overload of String.split to split words around the first space:
public static String reverse(String words) {
String[] wordArr = words.split(" ", 2); // split into a maximum of 2 Strings
if (wordArr.length > 1) { // If there is more than 1 word
// return the first word (wordArr[0]),
// behind the reverse of the rest of the String (wordArr[1])
return reverse(wordArr[1]) + " " + wordArr[0];
}
return wordArr[0]; // else, just return the one word
}
You shouldn't call nextLine() because your input is all on one line. Your logic is much clearer if you begin by creating a simple helper method, it should take an array of words and a position; from there you can recursively build your desired output with something like
private static String reverse(String[] words, int p) {
if (p + 1 < words.length) {
return reverse(words, p + 1) + " " + words[p];
} else if (p < words.length) {
return words[p];
}
return "";
}
Then your public method is easy to implement, just split the original input on white space and call reverse starting at 0 (remembering to return the result). Like,
public static String reverse(String words) {
return reverse(words.split("\\s+"), 0);
}
And then, I tested it like
public static void main(String[] args) {
System.out.println(reverse("Hello my friend"));
}
Which outputs (as requested)
friend my Hello
Alternatively, you could make that helper take your Scanner instead like
private static String reverse(Scanner sc) {
if (sc.hasNext()) {
String currentWord = sc.next();
if (sc.hasNext()) {
return reverse(sc) + " " + currentWord;
}
return currentWord;
}
return "";
}
And then your public method is
public static String reverse(String words) {
return reverse(new Scanner(words));
}
public static String reverseSentence(String sentence) {
StringBuilder sb = new StringBuilder();
int firstSpace = sentence.indexOf(' ');
if (firstSpace == -1) {
return sb.append(sentence.strip()).append(" ").toString();
}
String secondPart = sentence.substring(firstSpace + 1);
String firstPart = sentence.substring(0, firstSpace);//similar to merger sort
return sb.append(reverseSentence(secondPart)).append(reverseSentence(firstPart)).toString();
}
You throw away the recursion results:
reverse(sc.nextLine());
backwards = backwards + " " + currentWord;
Instead, use this:
backwards = reverse(sc.nextLine());
backwards = backwards + " " + currentWord;
Better yet:
backwards = reverse(sc.nextLine()) + " " + currentWord;
As stated in the comments, you could use a StringBuilder instead of Scanner class.
This example sends the same words, splits them by spaces each time you enter the method and you send the index of the word to be added in the next iteration.
For example:
public class RecursiveReverse {
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
String stringToReverse = "Hello my friend!";
System.out.println(reverse(stringToReverse, stringToReverse.split(" ").length - 1));
}
public static String reverse(String words, int i) {
if (i >= 0) { //If the index of the words is greater or equals the first word
sb.append(words.split(" ")[i]); //We split it and append it to our StringBuilder
sb.append(" "); //We append a space
reverse(words, --i); //We do this again
}
return sb.toString(); //When the above condition doesn't match we return the StringBuilder object as a String (which contains the words reversed)
}
}
Which produces this output:
friend! my Hello
A better method would be passing a String array as parameter so you split only once (when sending the words as an array to the method) the String.
public class RecursiveReverse {
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
String stringToReverse = "Hello my friend!";
String words[] = stringToReverse.split(" ");
System.out.println(reverse(words, words.length - 1));
}
public static String reverse(String words[], int i) {
if (i >= 0) {
sb.append(words[i]);
sb.append(" ");
reverse(words, --i);
}
return sb.toString();
}
}
Do you must use recursion? You can do that without it.
public static String reverse(String words) {
String[] list = words.split(" ");
Collections.reverse(list);
String reversed = String.join(" ", list);
return reversed;
}
You must keep hold of the extracted words between calls in an accumulator. Here is an example.
public static String reverse(String words, String acc){
Scanner sc = new Scanner(words);
if(!sc.hasNext()){
return acc;
}
return reverse(sc.nextLine(), acc) + " " + sc.next();
}
You would call it like this.
reverse("Hello my friend", "");
It's not the most efficient implementation in the world, but yeah... It must work!
If you want a more efficient one, use a StringBuilder as the accumulator.

Add Something to Char Array at Specific Spot (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"

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());

Java: method to get position of a match in a String?

String match = "hello";
String text = "0123456789hello0123456789";
int position = getPosition(match, text); // should be 10, is there such a method?
The family of methods that does this are:
int indexOf(String str)
indexOf(String str, int fromIndex)
int lastIndexOf(String str)
lastIndexOf(String str, int fromIndex)
Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified index].
String text = "0123hello9012hello8901hello7890";
String word = "hello";
System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"
// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
System.out.println(i);
} // prints "4", "13", "22"
// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
System.out.println(i);
} // prints "22", "13", "4"
This works using regex.
String text = "I love you so much";
String wordToFind = "love";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
while (match.find()) {
System.out.println("Found love at index "+ match.start() +" - "+ (match.end()-1));
}
Output :
Found 'love' at index 2 - 5
General Rule :
Regex search left to right, and once the match characters has been used, it cannot be reused.
text.indexOf(match);
See the String javadoc
Finding a single index
As others have said, use text.indexOf(match) to find a single match.
String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10
Finding multiple indexes
Because of #StephenC's comment about code maintainability and my own difficulty in understanding #polygenelubricants' answer, I wanted to find another way to get all the indexes of a match in a text string. The following code (which is modified from this answer) does so:
String text = "0123hello9012hello8901hello7890";
String match = "hello";
int index = text.indexOf(match);
int matchLength = match.length();
while (index >= 0) { // indexOf returns -1 if no match found
System.out.println(index);
index = text.indexOf(match, index + matchLength);
}
You can get all matches in a file simply by assigning inside while-loop, cool:
$ javac MatchTest.java
$ java MatchTest
1
16
31
46
$ cat MatchTest.java
import java.util.*;
import java.io.*;
public class MatchTest {
public static void main(String[] args){
String match = "hello";
String text = "hello0123456789hello0123456789hello1234567890hello3423243423232";
int i =0;
while((i=(text.indexOf(match,i)+1))>0)
System.out.println(i);
}
}
int match_position=text.indexOf(match);
import java.util.StringTokenizer;
public class Occourence {
public static void main(String[] args) {
String key=null,str ="my name noorus my name noorus";
int i=0,tot=0;
StringTokenizer st=new StringTokenizer(str," ");
while(st.hasMoreTokens())
{
tot=tot+1;
key = st.nextToken();
while((i=(str.indexOf(key,i)+1))>0)
{
System.out.println("position of "+key+" "+"is "+(i-1));
}
}
System.out.println("total words present in string "+tot);
}
}
I have some big code but working nicely....
class strDemo
{
public static void main(String args[])
{
String s1=new String("The Ghost of The Arabean Sea");
String s2=new String ("The");
String s6=new String ("ehT");
StringBuffer s3;
StringBuffer s4=new StringBuffer(s1);
StringBuffer s5=new StringBuffer(s2);
char c1[]=new char[30];
char c2[]=new char[5];
char c3[]=new char[5];
s1.getChars(0,28,c1,0);
s2.getChars(0,3,c2,0);
s6.getChars(0,3,c3,0); s3=s4.reverse();
int pf=0,pl=0;
char c5[]=new char[30];
s3.getChars(0,28,c5,0);
for(int i=0;i<(s1.length()-s2.length());i++)
{
int j=0;
if(pf<=1)
{
while (c1[i+j]==c2[j] && j<=s2.length())
{
j++;
System.out.println(s2.length()+" "+j);
if(j>=s2.length())
{
System.out.println("first match of(The) :->"+i);
}
pf=pf+1;
}
}
}
for(int i=0;i<(s3.length()-s6.length()+1);i++)
{
int j=0;
if(pl<=1)
{
while (c5[i+j]==c3[j] && j<=s6.length())
{
j++;
System.out.println(s6.length()+" "+j);
if(j>=s6.length())
{
System.out.println((s3.length()-i-3));
pl=pl+1;
}
}
}
}
}
}
//finding a particular word any where inthe string and printing its index and occurence
class IndOc
{
public static void main(String[] args)
{
String s="this is hyderabad city and this is";
System.out.println("the given string is ");
System.out.println("----------"+s);
char ch[]=s.toCharArray();
System.out.println(" ----word is found at ");
int j=0,noc=0;
for(int i=0;i<ch.length;i++)
{
j=i;
if(ch[i]=='i' && ch[j+1]=='s')
{
System.out.println(" index "+i);
noc++;
}
}
System.out.println("----- no of occurences are "+noc);
}
}
String match = "hello";
String text = "0123456789hello0123456789hello";
int j = 0;
String indxOfmatch = "";
for (int i = -1; i < text.length()+1; i++) {
j = text.indexOf("hello", i);
if (i>=j && j > -1) {
indxOfmatch += text.indexOf("hello", i)+" ";
}
}
System.out.println(indxOfmatch);
If you're going to scan for 'n' matches of the search string, I'd recommend using regular expressions.
They have a steep learning curve, but they'll save you hours when it comes to complex searches.
for multiple occurrence and the character found in string??yes or no
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SubStringtest {
public static void main(String[] args)throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the string");
String str=br.readLine();
System.out.println("enter the character which you want");
CharSequence ch=br.readLine();
boolean bool=str.contains(ch);
System.out.println("the character found is " +bool);
int position=str.indexOf(ch.toString());
while(position>=0){
System.out.println("the index no of character is " +position);
position=str.indexOf(ch.toString(),position+1);
}
}
}
public int NumberWordsInText(String FullText_, String WordToFind_, int[] positions_)
{
int iii1=0;
int iii2=0;
int iii3=0;
while((iii1=(FullText_.indexOf(WordToFind_,iii1)+1))>0){iii2=iii2+1;}
// iii2 is the number of the occurences
if(iii2>0) {
positions_ = new int[iii2];
while ((iii1 = (FullText_.indexOf(WordToFind_, iii1) + 1)) > 0) {
positions_[iii3] = iii1-1;
iii3 = iii3 + 1;
System.out.println("position=" + positions_[iii3 - 1]);
}
}
return iii2;
}
class Main{
public static int string(String str, String str1){
for (int i = 0; i <= str.length() - str1.length(); i++){
int j;
for (j = 0; j < str1.length(); j++) {
if (str1.charAt(j) != str.charAt(i + j)) {
break;
}
}
if (j == str1.length()) {
return i;
}}
return -1;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String str=sc.nextLine();
System.out.println("Enter the Substring");
String str1=sc.nextLine();
System.out.println("The position of the Substring is "+string(str, str1));
}
}

Categories