Is there a method to switch out a letter in a String? - java

I need a method that switches a letter from a specific index with another letter. Is there anything like it?
Like so:
String word = "test";
String letter = "e";
String secretWord = "????";
find the index of letter e and then find if e is in word. Then switch a "?" based on the index of the e in test.
So it would be ?e?? for secretWord.

You could use regex to search and replace any character that ISN'T letter:
String word = "test";
String secretWord = word.replaceAll("(?i)[^e]", "?");
You can also add more letters you don't want replaced to the regex (this would replace every non-vowel):
String secretWord = word.replaceAll("(?i)[^aeiouy]", "?");
Explanation of regex:
(?i) means "case-insensitive".
^ means "NOT".
aeiouy is the characters we DON'T want to match
Here's a demo of the regex replacement (just with e):
DEMO

string word = "test";
char letter = 'e';
string secretWord = "????";
int index = word.indexOf(letter);
if(index >= 0)
{
secretWord = secretWord.substring(0,index)+letter+secretWord.substring(index + 1);
System.out.println(secretWord);
}
This Code is for JAVA...... Try it

If you are using C# then try the Below coding.. It will help you
//Declare
string word = "test";
char letter = 'e';
string secretWord = "????";
if (word.IndexOf("e") != -1)//Find the Char is found or NOT
{
int index = word.IndexOf(letter); //Index of the Char
Console.WriteLine("Index of the Word E :" + word.IndexOf("e").ToString());
StringBuilder sb = new StringBuilder(secretWord);
sb[index] = letter; // Replacing the Char
secretWord = sb.ToString();
Console.WriteLine(secretWord);
}

I'd look at the task a bit differently. We have a secret ("test") and a way to display it, the result would be "????" or "?e??" if the letter e was provided. The sequence of ? is not a String itself but will be generated on demand. Then we don't have to replace something in a String (what we can't do, by the way, because strings are immutable). Here's the idea written in code:
public class SecretWord {
private String secret;
public SecretWord(String secret) {
this.secret = secret;
}
public String display(char c) {
if (secret == null) {
return "";
}
StringBuilder displayBuilder = new StringBuilder();
for (char secretChar : secret.toCharArray()) {
displayBuilder.append(secretChar == c ? c : '?');
}
return displayBuilder.toString();
}
}

I don't have enough rep to reply in a comment as yet, but you could expand on h2ooooo's post by adding in a variable to make it flexible, also:
String letter = "e";
String secretWord = word.replaceAll("(?i)[^" + letter + "]", "?");
+1, h2ooooo - tidy answer!
Westie

Related

I want to remove the special character and convert the next letter to uppercase "the-stealth-warrior" in Java

public class Main {
public static void main(String[] args) {
String name = "the-stealth-warrior";
for (int i = 0; i < name.length();i++){
if (name.charAt(i) == '-'){
char newName = Character.toUpperCase(name.charAt(i+1));
newName += name.charAt(i + 1);
i++;
}
}
}
}
I try to loop in every char and check if the I == '-' convert the next letter to be uppercase and append to a new String.
We can try using a split approach with the help of a stream:
String name = "the-stealth-warrior";
String parts = name.replaceAll("^.*?-", "");
String output = Arrays.stream(parts.split("-"))
.map(x -> x.substring(0, 1).toUpperCase() + x.substring(1))
.collect(Collectors.joining(""));
output = name.split("-", 2)[0] + output;
System.out.println(output); // theStealthWarrior
I think the most concise way to do this would be with regexes:
String newName = Pattern.compile("-+(.)?").matcher(name).replaceAll(mr -> mr.group(1).toUpperCase());
Note that Pattern.compile(...) can be stored rather than re-evaluating it each time.
A more verbose (but probably more efficient way) to do it would be to build the string using a StringBuilder:
StringBuilder sb = new StringBuilder(name.length());
boolean uc = false; // Flag to know whether to uppercase the char.
int len = name.codePointsCount(0, name.length());
for (int i = 0; i < name.len; ++i) {
int c = name.codePointAt(i);
if (c == '-') {
// Don't append the codepoint, but flag to uppercase the next codepoint
// that isn't a '-'.
uc = true;
} else {
if (uc) {
c = Character.toUpperCase(c);
uc = false;
}
sb.appendCodePoint(c);
}
}
String newName = sb.toString();
Note that you can't reliably uppercase single codepoints in specific locales, e.g. ß in Locale.GERMAN.

Upper case conversion - convert the first letter of each word in the string to uppercase

Some test cases are not working. May I know where I went Wrong. the test case "i love programming is working but other test case which idk are not working.
class Solution
{
public String transform(String s)
{
// code here
char ch;
// String s = "i love programming";
String res="";
ch = s.charAt(0);
ch = Character.toUpperCase(s.charAt(0));
res +=ch;
for(int i=1;i<s.length();i++){
if(s.charAt(i) == ' '){
//System.out.println(i);
ch = Character.toUpperCase(s.charAt(i+1));
res+=' ';
res+=ch;
i++;
}else {
res+=s.charAt(i);
}
}
return res;
}
}
//Some test cases are not working. May I know where I went Wrong?
This solution worked for me really well all the test cases passed. Thank you.
class Solution
{
public String transform(String s)
{
// code here
char ch;
// String s = "i love programming";
String res="";
ch = s.charAt(0);
ch = Character.toUpperCase(s.charAt(0));
res +=ch;
for(int i=1;i<s.length();i++){
if(s.charAt(i-1) == ' '){
//System.out.println(i);
ch = Character.toUpperCase(s.charAt(i));
res+=ch;
}else {
res+=s.charAt(i);
}
}
return res;
}
}
I tried my best to understand your code as the formatting got a bit butchered in markdown I am assuming but nevertheless I gathered that this was close to what your solution was:
public class MyClass {
public static void main(String args[]) {
int i = 0;
String greet = "hello world";
String res = "";
res += Character.toUpperCase(greet.charAt(i++));
for (; i < greet.length(); i++){
if (greet.charAt(i) == ' '){
res = res + greet.charAt(i) + Character.toUpperCase(greet.charAt(i + 1) );
i++;
}else{
res += greet.charAt(i);
}
}
System.out.println(res);
}
}
For me this worked, but this is assuming that spaces only ever occur between words. Perhaps the answer to your question lies in these test cases and more importantly the assumptions behind these test cases. Try to gather more info about that if you can :)
There is an attempt to make uppercase a next character after the space (which should be done only if this character is a letter and if this charactrer is available). Similarly the first character of the sentence is upper cased without checking if this first letter is a letter.
It may be better to use a boolean flag which should be reset upon applying an upper case to a letter. Also, StringBuilder should be used instead of concatenating a String in the loop.
So the improved code may look as follows with more rules added:
make the first letter in the word consisting of letters and/or digits upper case
words are separated with any non-letter/non-digit character except ' used in contractions like I'm, there's etc.
check for null/ empty input
public static String transform(String s) {
if (null == s || s.isEmpty()) {
return s;
}
boolean useUpper = true; // boolean flag
StringBuilder sb = new StringBuilder(s.length());
for (char c : s.toCharArray()) {
if (Character.isLetter(c) || Character.isDigit(c)) {
if (useUpper) {
c = Character.toUpperCase(c);
useUpper = false;
}
} else if (c != '\'') { // any non-alphanumeric character, not only space
useUpper = true; // set flag for the next letter
}
sb.append(c);
}
return sb.toString();
}
Tests:
String[] tests = {
"hello world",
" hi there,what's up?",
"-a-b-c-d",
"ID's 123abc-567def"
};
for (String t : tests) {
System.out.println(t + " -> " + transform(t));
}
Output:
hello world -> Hello World
hi there, what's up? -> Hi There,What's Up?
-a-b-c-d -> -A-B-C-D
ID's 123abc-567def -> ID's 123abc-567def
Update
A regular expression and Matcher::replaceAll(Function<MatchResult, String> replacer) available since Java 9 may also help to capitalize the first letters in the words:
// pattern to detect the first letter
private static final Pattern FIRST_LETTER = Pattern.compile("\\b(?<!')(\\p{L})([\\p{L}\\p{N}]*?\\b)");
public static String transformRegex(String s) {
if (null == s || s.isEmpty()) {
return s;
}
return FIRST_LETTER.matcher(s)
.replaceAll((mr) -> mr.group(1).toUpperCase() + mr.group(2));
}
Here:
\b - word boundary
(?<!') - negative lookbehind for ' as above, that is, match a letter NOT preceded with '
\p{L} - the first letter in the word (Unicode)
([\p{L}\p{N}]*\b) - followed by a possibly empty sequence of letters/digits

Uppercase or Lowercase a specific character in a word "Java"

I have look into most of questions but I couldn't find how to uppercase or lowercase specific character inside a word.
Example:
String name = "Robert"
What if I would like to make "b" Uppercase and rest lowercase also how to make first letter Uppercase and rest lowercase?
Like "john" >> Output >> "John"...
I have toUppercase() and toLowercase(). They convert the whole text.
Also I tried to include charAt but never worked with me.
You will need to take your string, take a substring of the specific character or characters you want to capitalize or lowercase, and then build a new string off of it.
Example
String test = "JoHn"; //make the H lowercase
test = test.substring(0,2) + test.substring(2,3).toLowercase() + test.substring(3);
The first substring gets all characters before the desired point, the second gets the desired character and lowercases it, and the final substring gets the rest of the string
You can use toCharArray() to capitalize the first letter like this:
String name = "robert";
// Convert String to char array.
char[] arr = name.toCharArray();
// Modify first element in array.
arr[0] = Character.toUpperCase(arr[0]);
String str = new String(arr);
System.out.println(str);
Output:
Robert
And you want to make "b" Uppercase and rest lowercase like this:
// Convert String to char array.
char[] arr2 = name.toCharArray();
// Modify the third element in array.
arr2[2] = Character.toUpperCase(arr2[2]);
String str2 = new String(arr2);
System.out.println(str2);
Output:
roBert
//Try this...
String str = "Robert";
for (int i = 0; i < str.length(); i++) {
int aChar = str.charAt(i);
// you can directly use character instead of ascii codes
if (aChar == 'b') {
aChar = aChar - 32;
} else if (aChar >= 'A' && aChar <= 'Z') {
aChar += 32 ;
}
System.out.print((char) aChar);
}
/*
Output will be- roBert
*/
I wouldn't use 'test.substring(2, 3).toLowerCase()' necessarily. 'Character.valueOf(test.charAt(2)).toUpperCase()' works. Also, the 'test.substring(0, 3)' is wrong; it should be 'test.substring(0, 2)'.
A function that capitalize the first letter
private String capitalize(String str) {
return Character.toUpperCase(str.charAt(0)) + str.substring(1);
}
A function that capitalize an arbitrary letter
private String replaceCharWithUpperCase(char letterToCapitalize, String str)
{
return str.replaceAll(letterToCapitalize, Character.toUpperCase(letterToCapitalize));
}
Then you can use the previous functions like that :
String a = "JOHN";
a = capitalize(a.toLowerCase());
// now a = John.
String b = "ROBERT";
a = replaceCharWithUpperCase('b', a.toLowerCase());
// now a = roBert.

how to insert '*' before 'S' and '*' after 'S' in StringBuffer java

How to insert * before S and * after S
StringBuffer Java?
StringBuffer textInFile= new StringBuffer ("Stanford ");
public void convertToPTD(PlainTextDocument ptd)
{
if(ptd.textInFile.charAt(i)=='S')
{
ptd.textInFile.......???
}
System.out.println(ptd.textInFile);
return;
}
Use the .replace method. An example:
char c = '*';
String s = "S";
String str = "Stanford";
String rep = str.replace(s, c + s + c);
Your first step is to find the list of indices where "S" is.
Your second step is, for each index, replace "S" with "*S*".
Here is how:
int i = -1;
while (true) {
i = buffer.indexOf(i + 1, "S");
if (i == -1) break; // No more occurrences of "S" are found
buffer = buffer.replace(i, i + 1, "*S*");
}
indexOf() returns -1 if there are no occurrences of the substring we want in the section of the String we're looking at.
You could use it recursively to suit your needs.
Below is a piece of code I have tested on my machine. Hope it works for you:
StringBuffer str = new StringBuffer("WhereStanford");
str = str.replace(str.indexOf("S", 0), str.indexOf("S", 0)+1, "*S*");

Breaking Strings into chars that are in upper case

I'm making a method to read a whole class code and do some stuff with it.
What I want to do is get the name of the method, and make a String with it.
Something like removeProduct
I'll make a String "Remove Product"
How can I split the name method in capital cases?
How can I build this new string with the first letter of each word as capital case?
I'm doing it with substring, is there a easier and better way to do it?
ps: I'm sure my brazilian English didn't help on title. If anyone can make it looks better, I'd appreciate.
Don't bother reinvent the wheel, use the method in commons-lang
String input = "methodName";
String[] words = StringUtils.splitByCharacterTypeCamelCase(methodName);
String humanised = StringUtils.join(words, ' ');
You can use a regular expression to split the name into the various words, and then capitalize the first one:
public static void main(String[] args) {
String input = "removeProduct";
//split into words
String[] words = input.split("(?=[A-Z])");
words[0] = capitalizeFirstLetter(words[0]);
//join
StringBuilder builder = new StringBuilder();
for ( String s : words ) {
builder.append(s).append(" ");
}
System.out.println(builder.toString());
}
private static String capitalizeFirstLetter(String in) {
return in.substring(0, 1).toUpperCase() + in.substring(1);
}
Note that this needs better corner case handling, such as not appending a space at the end and handling 1-char words.
Edit: I meant to explain the regex. The regular expression (?=[A-Z]) is a zero-width assertion (positive lookahead) matching a position where the next character is between 'A' and 'Z'.
You can do this in 2 steps:
1 - Make the first letter of the string uppercase.
2 - Insert an space before an uppercase letter which is preceded by a lowercase letter.
For step 1 you can use a function and for step 2 you can use String.replaceAll method:
String str = "removeProduct";
str = capitalizeFirst(str);
str = str.replaceAll("(?<=[^A-Z])([A-Z])"," $1");
static String capitalizeFirst(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1);
}
Code In Action
#MrWiggles is right.
Just one more way to do this without being fancy :)
import java.util.StringTokenizer;
public class StringUtil {
public static String captilizeFirstLetter(String token) {
return Character.toUpperCase(token.charAt(0)) + token.substring(1);
}
public static String convert(String str) {
final StringTokenizer st = new StringTokenizer(str,
"A B C D E F G H I J K L M N O P Q R S T U V W X Y Z", true);
final StringBuilder sb = new StringBuilder();
String token;
if (st.hasMoreTokens()) {
token = st.nextToken();
sb.append(StringUtil.captilizeFirstLetter(token) + " ");
}
while (st.hasMoreTokens()) {
token = st.nextToken();
if (st.hasMoreTokens()) {
token = token + st.nextToken();
}
sb.append(StringUtil.captilizeFirstLetter(token) + " ");
}
return sb.toString().trim();
}
public static void main(String[] args) throws Exception {
String words = StringUtil.convert("helloWorldHowAreYou");
System.out.println(words);
}
}
public String convertMethodName(String methodName) {
StringBuilder sb = new StringBuilder().append(Character.toUpperCase(methodName.charAt(0)));
for (int i = 1; i < methodName.length(); i++) {
char c = methodName.charAt(i);
if (Character.isUpperCase(c)) {
sb.append(' ');
}
sb.append(c);
}
return sb.toString();
}
Handling it this way may give you some finer control in case you want to add in functionality later for other situations (multiple caps in a row, etc.). Basically, for each character, it just checks to see if it's within the bounds of capital letters (character codes 65-90, inclusive), and if so, adds a space to the buffer before the word begins.
EDIT: Using Character.isUpperCase()

Categories

Resources