I would like to know how to print a particular index to Upper and Lower Case?
I don't know for the particular index to change?
For single index this is the code...
public class UpperAndLowerCase {
public static void main(String[] args) {
String input="India";
int index=input.indexOf('i');
String result=input.substring(0,index)+input.substring(index,index+1).toUpperCase()+input.substring(index+1);
System.out.println(result);
}
}
The output of this program is : IndIa
But I want the output like this: indIa (In a given input String, first 'I' to 'i' and next 'i' to 'I')
Below is generic implementation which will give you expected result.
public static void main(String[] args) {
String input = "India";
String newInput = replaceCharacterToUpperCase(input, 'i', true);
System.out.println(newInput);
String newInput2 = replaceCharacterToLowerCase(newInput, 'I', false);
System.out.println(newInput2);
}
/**
*
* #param input: Input string to work on.
* #param c: Character to convert case
* #param isAllOccurance: Whether to replace all occurrence or single occurrence
* #return
*/
private static String replaceCharacterToUpperCase(String input, char c, boolean isAllOccurance) {
int index = input.indexOf(c);
if(isAllOccurance){
return input.replace(input.charAt(index), Character.toUpperCase(input.charAt(index)));
} else{
return input.replaceFirst(Character.toString(input.charAt(index)), Character.toString(Character.toUpperCase(input.charAt(index))));
}
}
/**
*
* #param input: Input string to work on.
* #param c: Character to convert case
* #param isAllOccurance: Whether to replace all occurrence or single occurrence
* #return
*/
private static String replaceCharacterToLowerCase(String input, char c, boolean isAllOccurance) {
int index = input.indexOf(c);
if(isAllOccurance){
return input.replace(input.charAt(index), Character.toLowerCase(input.charAt(index)));
} else{
return input.replaceFirst(Character.toString(input.charAt(index)), Character.toString(Character.toLowerCase(input.charAt(index))));
}
}
Disclaimer: This is not tested exhaustively to cover all possible requirements or scenarios anybody can have, so on basis of your special requirement you may need to tweak the things a bit.
Basically to replace single character in a String, you can use below code:
int index=input.indexOf('i');
String newInput = input.replace(input.charAt(index), Character.toUpperCase(input.charAt(index)));
There are many methods in String class which lets you do replacements, based on your requirement like whether character or string, first occurrenceor all occurrence. Methods like:
replaceFirst(String regex, String replacement)
replaceAll(String regex, String replacement)
replace(CharSequence target, CharSequence replacement)
Related
i got a problem here guys. I need to get all the numbers from a string here from a list of strings.
Lets say one of the strings in the list is "Jhon [B] - 14, 15, 16"
and the format of the strings is constant, every string has maximum of 7 numbers in it and the numbers are separated with "," . I want to get every number after the "-". i am really confused here, i tried everything i know of but i am not getting even close.
public static List<String> readInput() {
final Scanner scan = new Scanner(System.in);
final List<String> items = new ArrayList<>();
while (scan.hasNextLine()) {
items.add(scan.nextLine());
}
return items;
}
public static void main(String[] args) {
final List<String> stats= readInput();
}
}
You could...
Just manually parse the String using things like String#indexOf and String#split (and String#trim)
String text = "Jhon [B] - 14, 15, 16";
int indexOfDash = text.indexOf("-");
if (indexOfDash < 0 && indexOfDash + 1 < text.length()) {
return;
}
String trailingText = text.substring(indexOfDash + 1).trim();
String[] parts = trailingText.split(",");
// There's probably a really sweet and awesome
// way to use Streams, but the point is to try
// and keep it simple 😜
List<Integer> values = new ArrayList<>(parts.length);
for (int index = 0; index < parts.length; index++) {
values.add(Integer.parseInt(parts[index].trim()));
}
System.out.println(values);
which prints
[14, 15, 16]
You could...
Make use of a custom delimiter for Scanner for example...
String text = "Jhon [B] - 14, 15, 16";
Scanner parser = new Scanner(text);
parser.useDelimiter(" - ");
if (!parser.hasNext()) {
// This is an error
return;
}
// We know that the string has leading text before the "-"
parser.next();
if (!parser.hasNext()) {
// This is an error
return;
}
String trailingText = parser.next();
parser = new Scanner(trailingText);
parser.useDelimiter(", ");
List<Integer> values = new ArrayList<>(8);
while (parser.hasNextInt()) {
values.add(parser.nextInt());
}
System.out.println(values);
which prints...
[14, 15, 16]
Or You could use a method that will extract signed or unsigned Whole or floating point numbers from a string. The method below makes use of the String#replaceAll() method:
/**
* This method will extract all signed or unsigned Whole or floating point
* numbers from a supplied String. The numbers extracted are placed into a
* String[] array in the order of occurrence and returned.<br><br>
*
* It doesn't matter if the numbers within the supplied String have leading
* or trailing non-numerical (alpha) characters attached to them.<br><br>
*
* A Locale can also be optionally supplied so to use whatever decimal symbol
* that is desired otherwise, the decimal symbol for the system's current
* default locale is used.
*
* #param inputString (String) The supplied string to extract all the numbers
* from.<br>
*
* #param desiredLocale (Optional - Locale varArgs) If a locale is desired for a
* specific decimal symbol then that locale can be optionally
* supplied here. Only one Locale argument is expected and used
* if supplied.<br>
*
* #return (String[] Array) A String[] array is returned with each element of
* that array containing a number extracted from the supplied
* Input String in the order of occurrence.
*/
public static String[] getNumbersFromString(String inputString, java.util.Locale... desiredLocale) {
// Get the decimal symbol the the current system's locale.
char decimalSeparator = new java.text.DecimalFormatSymbols().getDecimalSeparator();
/* Is there a supplied Locale? If so, set the decimal
separator to that for the supplied locale */
if (desiredLocale != null && desiredLocale.length > 0) {
decimalSeparator = new java.text.DecimalFormatSymbols(desiredLocale[0]).getDecimalSeparator();
}
/* The first replaceAll() removes all dashes (-) that are preceeded
or followed by whitespaces. The second replaceAll() removes all
periods from the input string except those that part of a floating
point number. The third replaceAll() removes everything else except
the actual numbers. */
return inputString.replaceAll("\\s*\\-\\s{1,}","")
.replaceAll("\\.(?![\\d](\\.[\\d])?)", "")
.replaceAll("[^-?\\d+" + decimalSeparator + "\\d+]", " ")
.trim().split("\\s+");
}
I'm trying to find the strings in a TreeSet<String> that start with a given prefix. I found a previous question asking for the same thing — Searching for a record in a TreeSet on the fly — but the answer given there doesn't work for me, because it assumes that the strings don't include Character.MAX_VALUE, and mine can.
(The answer there is to use treeSet.subSet(prefix, prefix + Character.MAX_VALUE), which gives all strings between prefix (inclusive) and prefix + Character.MAX_VALUE (exclusive), which comes out to all strings that start with prefix except those that start with prefix + Character.MAX_VALUE. But in my case I need to find all strings that start with prefix, including those that start with prefix + Character.MAX_VALUE.)
How can I do this?
To start with, I suggest re-examining your requirements. Character.MAX_VALUE is U+FFFF, which is not a valid Unicode character and never will be; so I can't think of a good reason why you would need to support it.
But if there's a good reason for that requirement, then — you need to "increment" your prefix to compute the least string that's greater than all strings starting with your prefix. For example, given "city", you need "citz". You can do that as follows:
/**
* #param prefix
* #return The least string that's greater than all strings starting with
* prefix, if one exists. Otherwise, returns Optional.empty().
* (Specifically, returns Optional.empty() if the prefix is the
* empty string, or is just a sequence of Character.MAX_VALUE-s.)
*/
private static Optional<String> incrementPrefix(final String prefix) {
final StringBuilder sb = new StringBuilder(prefix);
// remove any trailing occurrences of Character.MAX_VALUE:
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == Character.MAX_VALUE) {
sb.setLength(sb.length() - 1);
}
// if the prefix is empty, then there's no upper bound:
if (sb.length() == 0) {
return Optional.empty();
}
// otherwise, increment the last character and return the result:
sb.setCharAt(sb.length() - 1, (char) (sb.charAt(sb.length() - 1) + 1));
return Optional.of(sb.toString());
}
To use it, you need to use subSet when the above method returns a string, and tailSet when it returns nothing:
/**
* #param allElements - a SortedSet of strings. This set must use the
* natural string ordering; otherwise this method
* may not behave as intended.
* #param prefix
* #return The subset of allElements containing the strings that start
* with prefix.
*/
private static SortedSet<String> getElementsWithPrefix(
final SortedSet<String> allElements, final String prefix) {
final Optional<String> endpoint = incrementPrefix(prefix);
if (endpoint.isPresent()) {
return allElements.subSet(prefix, endpoint.get());
} else {
return allElements.tailSet(prefix);
}
}
See it in action at: http://ideone.com/YvO4b3.
If anybody is looking for a shorter version of ruakh's answer:
First element is actually set.ceiling(prefix),and last - you have to increment the prefix and use set.floor(next_prefix)
public NavigableSet<String> subSetWithPrefix(NavigableSet<String> set, String prefix) {
String first = set.ceiling(prefix);
char[] chars = prefix.toCharArray();
if(chars.length>0)
chars[chars.length-1] = (char) (chars[chars.length-1]+1);
String last = set.floor(new String(chars));
if(first==null || last==null || last.compareTo(first)<0)
return new TreeSet<>();
return set.subSet(first, true, last, true);
}
could someone please explain how the return line works?
Thank you
public class JavaApplication1 {
/**
* Repeat string <b>str</b> <b>times</b> time.
* #param str string to repeat
* #param times repeat str times time
* #return generated string
*/
public static String repeat(String str, int times) {
return new String(new char[times]).replace("\0", str);
}
public static void main(String[] args) {
System.out.println(repeat("*", 5));
}
}
It is easier to follow if it is broken down step by step
// str = "*" and times = 5
public static String repeat(String str, int times) {
//we crete a new empty array which will have values {'\0','\0','\0','\0','\0'}
char[] charArray = new char[times]();
String newstr = new String(charArray); // newstr.equals("\0\0\0\0\0")
newstr = newstr.replace('\0', str); //we now replace all '\0' with "*"
return newstr; //newstr.equals("*****")
}
constructor String(char[] value)
Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
Not sure what is char[] contains in your code and what actually you are intended to do. return method can be also be done as follows,which might make you understand.
This is similar to
public class JavaApplication1 {
/**
* Repeat string <b>str</b> <b>times</b> time.
* #param str string to repeat
* #param times repeat str times time
* #return generated string
*/
public static String repeat(String str, int times) {
String sampleString=new String(new char[times]).replace("\0", str);
return sampleString;
}
public static void main(String[] args) {
System.out.println(repeat("*", 5));
}
}
Take if from the inside out: new char[times] creates a character array of size times, an integer value passed in on the call to repeat. The replace method then replaces each occurrence of the null value in the character array with the str parameter, the asterisk in your case. Since the new character array is initialized by default with the null character, \0, the replacement takes place for each element in the array. You should get a string of 5 asterisks when you run the program.
I'm trying to write code that tells the user if a word they input is a palindrome or not.
I am using a recursive method to reverse the word, but it isn't terminating correctly. The StackOverFlowError appears when I test it out. My terminating code looks correct to me, so I'm not sure why it isn't working.
Also, when I try to make the String object all lower case characters, does the debugger show that the word was made all lower case, or does it just stay the same?
Here is the code:
public class Palindrome
{
private String word;
/**
* Constructor for objects of class PalindromeTester
*/
public Palindrome(String supposedPalindrome)
{
word = supposedPalindrome;
}
/**
* Tests if the word is a palindrome or not.
*/
public void testPalindrome()
{
String reversed = reverse();
if(reversed.equals(word.toLowerCase()))
{
System.out.println(word + " is a palindrome!");
}
else
{
System.out.println(word + " is not a palindrome.");
}
}
/**
* Reverses the word.
*
* #return the reversed string.
*/
private String reverse()
{
return reverseHelper(word);
}
/**
* A recursive method that reverses the String for the
* reverse the string method.
*
* #return the reversed string.
*/
private String reverseHelper(String s)
{
s.toLowerCase();
if(s.length() <= 1)
{
return s;
}
else
{
return reverseHelper(s.substring(1, s.length()) + s.charAt(0));
}
}
}
Thank you for your help!
Why use a recursive system when there's a built-in way?
public class Palindrome() {
public Palindrome(String supposedPalindrome) {
if( supposedPalindrome.equals(new StringBuffer(supposedPalindrome).reverse().toString())) {
System.out.println(supposedPalindrome+" is a palindrome!");
}
else {
System.out.println(supposedPalindrome+" is not a palindrome!");
}
}
}
Or something like that, using StringBuffer's built-in reverse() method.
two mistakes in your code:
String are immutable
so doing s.toLowerCase() won't make any changes to s, you need to assign in back to an String
s = s.toLowerCase();
Your recursive method is buggy
return reverseHelper(s.substring(1, s.length()) + s.charAt(0));
it always passes String of length s.length() (I mean if String s is of length 5 then you recursive call is always passing string of length 5 only with only position of characters being changed)
Suggestion:
make you recursive call to shorten you string each time so that it finally matches if condition after string has been reversed
Or use StringBuilder#reverse() method to reverse your string
Strings are immutable. String.toLowerCase(String) returns a new String.
Replace
s.toLowerCase();
with
s = s.toLowerCase();
or even better
return reverseHelper(word.toLowerCase());
and remove
s.toLowerCase();
I want to convert the first character of a string to Uppercase and the rest of the characters to lowercase. How can I do it?
Example:
String inputval="ABCb" OR "a123BC_DET" or "aBcd"
String outputval="Abcb" or "A123bc_det" or "Abcd"
Try this on for size:
String properCase (String inputVal) {
// Empty strings should be returned as-is.
if (inputVal.length() == 0) return "";
// Strings with only one character uppercased.
if (inputVal.length() == 1) return inputVal.toUpperCase();
// Otherwise uppercase first letter, lowercase the rest.
return inputVal.substring(0,1).toUpperCase()
+ inputVal.substring(1).toLowerCase();
}
It basically handles special cases of empty and one-character string first and correctly cases a two-plus-character string otherwise. And, as pointed out in a comment, the one-character special case isn't needed for functionality but I still prefer to be explicit, especially if it results in fewer useless calls, such as substring to get an empty string, lower-casing it, then appending it as well.
String a = "ABCD"
using this
a.toLowerCase();
all letters will convert to simple, "abcd"
using this
a.toUpperCase()
all letters will convert to Capital, "ABCD"
this conver first letter to capital:
a.substring(0,1).toUpperCase()
this conver other letter Simple
a.substring(1).toLowerCase();
we can get sum of these two
a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();
result = "Abcd"
WordUtils.capitalizeFully(str) from apache commons-lang has the exact semantics as required.
String inputval="ABCb";
String result = inputval.substring(0,1).toUpperCase() + inputval.substring(1).toLowerCase();
Would change "ABCb" to "Abcb"
I consider this simpler than any prior correct answer. I'll also throw in javadoc. :-)
/**
* Converts the given string to title case, where the first
* letter is capitalized and the rest of the string is in
* lower case.
*
* #param s a string with unknown capitalization
* #return a title-case version of the string
*/
public static String toTitleCase(String s)
{
if (s.isEmpty())
{
return s;
}
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
Strings of length 1 do not needed to be treated as a special case because s.substring(1) returns the empty string when s has length 1.
/* This code is just for convert a single uppercase character to lowercase
character & vice versa.................*/
/* This code is made without java library function, and also uses run time input...*/
import java.util.Scanner;
class CaseConvert {
char c;
void input(){
//#SuppressWarnings("resource") //only eclipse users..
Scanner in =new Scanner(System.in); //for Run time input
System.out.print("\n Enter Any Character :");
c=in.next().charAt(0); // input a single character
}
void convert(){
if(c>=65 && c<=90){
c=(char) (c+32);
System.out.print("Converted to Lowercase :"+c);
}
else if(c>=97&&c<=122){
c=(char) (c-32);
System.out.print("Converted to Uppercase :"+c);
}
else
System.out.println("invalid Character Entered :" +c);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CaseConvert obj=new CaseConvert();
obj.input();
obj.convert();
}
}
/*OUTPUT..Enter Any Character :A Converted to Lowercase :a
Enter Any Character :a Converted to Uppercase :A
Enter Any Character :+invalid Character Entered :+*/