I am creating a CamelCase function in Java that takes a string this_is_a_sentence and returns ThisIsASentence My main problem comes with handeling the different characters in the string.
So far I have:
import java.util.Scanner;
public class Main{
public static String camelCaser(String str){
char[] strChr = str.toCharArray();
strChr[0] = strChr[0].toUpperCase;
for(int i = 0; i < strChr.length; i++){
if (strChr[i] == '_'){
strChr[i] = strChr[i+1].toUpperCase;
strChr[i+1] = "";
}
}
String newStr = new String(strChr);
return newStr;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("String: ");
String str = input.next();
System.out.printf("Converting: %s into %s", str, camelCaser(str));
}
}
My main problems seems to be that you can not alter individual characters the same way that I am used to in C. I have read that you can use a class called Character but I cant figure out how to use it. The Java documentation on the matter https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html did not help me either.
I changed around a bit of your logic to make this work. The easiest thing to make it work was to search the string for _, and then capitalize the following letter. After that, take the resulting string and remove all the _'s. It ended up like this:
import java.util.Scanner;
public class Caser{
public static String camelCaser(String str){
char[] strChr = str.toCharArray();
strChr[0] = Character.toUpperCase(strChr[0]);
for(int i = 0; i < strChr.length; i++) if (strChr[i] == '_') strChr[i+1] = Character.toUpperCase(strChr[i+1]);
String reply = new String(strChr);
reply = reply.replace("_", "");
return reply;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("String: ");
String str = input.next();
System.out.printf("Converting: %s into %s", str, camelCaser(str));
}
}
EDIT:
What does String reply = new String(strChr); do?
This creates a new variable named reply. The variable is a String. new String(strChr) is a helper that the String class has whereby you can give it a char[] and it will automatically turn it into a String.
What does reply = reply.replace("_", ""); do?
.replace(String, String) is a String method that will search said string (in this case, reply) and will search for all instances of _ and when it finds them it will replace it with an empty String (in this case, it is blank "").
This code has several problems. First, toUpperCase() cannot be used on a char, you'd need to call Character.toUpperCase(character). Second, strChar[i+1]=""; does not compile, as "" is the empty String, strChar is a array of char.
I'd do something like this: first, I would split the string by "_" if you're sure you only want this as your separating character using String[] words = str.split("_"). Then, I would create a new String which will be the result String (let's call it res). After that, I would loop over all elements in words, make the first character upper case, add it to res and add all the other characters of the current element to res.
So, it would look like this:
public static String camelCaser(String str){
String[] words = str.split("_"); // split str by _
String res = ""; // result string
for(String word : words) {
// first check, if words is empty
if(!word.isEmpty()) {
// add first character upper case
res += Character.toUpperCase(word.charAt(0));
// add remaining characters as they are, if any
if(word.length() > 1) {
res += word.substring(1);
}
}
}
return res;
}
You would need to do something like Character.toUpperCase(strChr[0]); to convert a character in your array to uppercase.
Use Character.toUpperCase(char).
public class Main{
public static String camelCaser(String str){
char[] strChr = str.toCharArray();
strChr[0] = Character.toUpperCase(strChr[0]);
for(int i = 0; i < strChr.length; i++){
if (strChr[i] == '_'){
strChr[i] = Character.toUpperCase(strChr[i+1]);
strChr[i+1] = Character.valueOf('\u0000') ;
}
}
String newStr = new String(strChr);
return newStr;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("String: ");
String str = input.next();
System.out.printf("Converting: %s into %s", str, camelCaser(str));
}
}
Related
How Would we write a program using Java to read a paragraph from the user and replace specific words mentioned in a vector to the following format, i.e.,
For example word Happy is reduced to H****.
Any Help will be Appriciated.
import java.io.*;
import java.util.*;
class replaceString {
public static String putStars(String str) {
char first_char = str.charAt(0);
String ans = new String();
ans = String.valueOf(first_char);
for(int i = 1;i < str.length(); ++i ) {
ans = ans + "*";
}
return ans;
}
public static String replaceWords(String str, Vector<String> v1) {
String[] words = str.split("\\W+"); //split across all types of punctuation
String ansString = new String();
for(String to_be_replaced : words) {
boolean found = false;
for(String to_replace_with : v1) {
if(to_be_replaced.equals(to_replace_with)) {
//System.out.println("in");
ansString = ansString +putStars(to_be_replaced) + " ";
found = true;
}
}
if(found == false) {
ansString = ansString + to_be_replaced + " ";
}
}
return ansString;
}
public static String replaceWords1(String str, Vector<String> v1) {
for(String currStr : v1) {
str.replace(str, );
}
return ansString;
}
public static void main(String args[])throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the paragraph that you would like to edit ");
String s = br.readLine();
// Let us assume some strings in our very own vector
Vector<String> v1 = new Vector<String>();
v1.addElement("Hello");
v1.addElement("Hi");
v1.addElement("Heya");
v1.addElement("Howdy");
v1.addElement("Howu");
String ans = replaceWords(s, v1);
System.out.println("Paragraph after replacement becomes\n\n"+ ans);
}
}
this is my current code but its not working fine
There could be other possibilities, but here's an example I did based on this answer:
We need all the words we need / want to match, and store them in an array:
String [] words = {"appy", "eya", "dy"};
(Optional) If you really need a Vector, I suggest to create a List (ArrayList) instead, and we can do it this way:
List <String> wordsToReplace = Arrays.asList(words);
Otherwise just modify the method in the next step to receive an array...
We create a function that receives this List and the phrase we want to check for and that returns the new String with the replaced text in it
So, our whole code ends up like this:
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WordReplacer {
public static void main(String[] args) {
String [] words = {"appy", "eya", "dy"};
List <String> wordsToReplace = Arrays.asList(words);
System.out.println(replaceWords("Happy", wordsToReplace));
System.out.println(replaceWords("Heya", wordsToReplace));
System.out.println(replaceWords("Howdy?", wordsToReplace));
System.out.println(replaceWords("Howdy? My friend lives in Pompeya and every time I see her I say \"Heya\" to her, she is very happy", wordsToReplace));
}
private static String replaceWords(String word, List <String> wordsToReplace) {
for (String s : wordsToReplace) {
Pattern p = Pattern.compile(s, Pattern.CASE_INSENSITIVE); //We create a pattern that matches each word in our list. (1)
Matcher m = p.matcher(word); //We actually check for each match against our phrase
StringBuilder sb = new StringBuilder();
if (m.find()) { //If there was a match, we're going to replace each character for an '*' (2)
for (int i = 0; i < s.length(); i++) {
sb.append("*");
}
}
word = m.replaceAll(sb.toString()); //We replace each match with '*' (3)
}
return word; //We return the modified word
}
}
I'm going to explain what each comment (1), (2), (3) do in a better and simpler way:
(1) As shown in the linked answer, they use \b regex command to match whole words, but in this case we're using it to match parts of words, not whole words, so we don't need it here...
(2) Only if we found a match we fill the StringBuilder with * characters... If we didn't do it this way, we would be getting: H* instead of H**** for the case of Happy word, this way we ensure we get the correct amount of * for every word in the List.
(3) We replace the matches for the total number of * in the StringBuilder so we get the correct output.
The program above produces the following output:
H****
H***
How**?
How**? My friend lives in Pomp*** and every time I see her I say "H***" to her, she is very h****
Try something like that with a map that contains yours replacing rules :
String input; //input string
Map<String,String> mapReplace = new HashMap<String,String>();
mapReplace.put("Hello","H****");
Iterator<String> keys = mapReplace.keySet().iterator();
while(keys.hasNext()){
String key = keys.next();
input = input.replace(input, mapReplace.get(key));
}
So I'm trying to write a method where it detects all the capital letters given by the user. How is this possible? Is it possible to do it using ASCII values? Is it possible in another way? Please give me suggestions and about the best way to come up with this algorithm
NOTE: problem is as stated at bottom of the source CODE
SOURCE CODE
Scanner sc = new Scanner(System.in);
private String userPassword;
private char[] passChar;
private int passwordScore = 0;
public String getPassword(){
userPassword = sc.nextLine();
passChar = userPassword.toCharArray();
return userPassword;
}
// Ingore this comment below, this is just for me
//do for( char i : passChar.length) or actualy if statmen so that if the pass is not 8 charaters long it doesnt qulafiy
public void passRequirments(){
}
public int passLength(){
for(char upperCase: passChar){
passwordScore = passwordScore + 4;
}
return passwordScore;
}
//THIS IS WHERE IM HAVING TROUBLE
public void passUpper(){
for (char c : passChar){
if (Character.isUpperCase(passChar.charAt(c))){
}
}
}
THE PROBLEM
public void passUpper(){
for (char c : passChar){
if (Character.isUpperCase(passChar.charAt(c))){
passwordScore = passwordScore + ((userPassword.length()- passChar.charAt(c)) * 2);
}
}
}
I think something like this could be a feasible solution
import java.io.*;
import java.util.*;
public class Main{
public static int printUpperCaseLetters(String s)
{
char[] ch = new char[s.length()];
ch = s.toCharArray();
int cap_count = 0;
for(int i=0; i<ch.length; i++)
{
int val = (int)ch[i];
if(val>=65 && val<=90)
{
cap_count++;
System.out.println(ch[i]);
}
}
return cap_count;
}
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
String s = input.next();
// So this method returns you the capital letters count inside of the string
int cap_count = printUpperCaseLetters(s);
}
}
Hope this help!
You can fetch the function part and add it to your code.
Just focus on the method printUpperCaseLetters and pass your String to this method.
Just use regex to replace all non capital letters to empty space:
string = string.replaceAll("[^A-Z]", "");
You will end up with string that contains only capital letters from input.
so i have split a string from a users input.
String p = blah.nextLine();
String[] pizzaArr = p.split("");
String s = pizzaArr[0];
String t= *pizzaArr[1][2][3][4]* <=== this is the bit.
i want the rest of the array i split without the first element to a string. i have demonstrated this with the elements there , this in fact doesn't work. i need this so i can use it in a switch (has to be a string)
String t= "";
for(int i = 1; i < pizzaArr.length; i++) {
t += pizzaArr[i];
}
Use scanner to take input string and split the string using split() method. split("") method split your string by one char. since your question is unclear, so what i understand is , use first char as a switch case. See the demo :
import java.util.Scanner;
/**
*
* #author Ataur
*/
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String p = sc.nextLine();
String[] pizzaArr = p.split("");
String output ="";
String switchStr = p.substring(0, 1);
for(int i= 1; i< pizzaArr.length;i++){
output+=pizzaArr[i];
}
System.out.println("This is the original String = "+output);
switch(switchStr){
case "1":{
System.out.println("In the switch case statement");
}
default:{
System.out.println("this is default statement");
}
}
}
}
The easiest way to achieve this would be to use String#join along with Arrays#copyOfRange:
String.join(" ", Arrays.copyOfRange(pizzaArr, 1, pizzaArr.length));
Note how it uses a single character of white-space as the delimiter; this can be changed by simply changing the first parameter of String#join to whatever you'd like!
I'm trying to create a palindrome tester program for my AP Java class and I need to remove the white spaces in my code completely but it's not letting me do so.
import java.util.Scanner;
public class Palin{
public static boolean isPalindrome(String stringToTest) {
String workingCopy = removeJunk(stringToTest);
String reversedCopy = reverse(workingCopy);
return reversedCopy.equalsIgnoreCase(workingCopy);
}
public static String removeJunk(String string) {
int i, len = string.length();
StringBuffer dest = new StringBuffer(len);
char c;
for (i = (len - 1); i >= 0; i-=1) {
c = string.charAt(i);
if (Character.isLetterOrDigit(c))
{
dest.append(c);
}
}
return dest.toString();
}
public static String reverse(String string) {
StringBuffer sb = new StringBuffer(string);
return sb.reverse().toString();
}
public static void main(String[] args) {
System.out.print("Enter Palindrome: ");
Scanner sc = new Scanner(System.in);
String string = sc.next();
String str = string;
String space = "";
String result = str.replaceAll("\\W", space);
System.out.println(result);
System.out.println();
System.out.println("Testing palindrome:");
System.out.println(" " + string);
System.out.println();
if (isPalindrome(result)) {
System.out.println("It's a palindrome!");
} else {
System.out.println("Not a palindrome!");
}
System.out.println();
}
}
Any help would be greatly appreciated.
Seems like your code is fine except for the following. You are using
String string = sc.next();
which will not read the whole line of input, hence you will lose part of the text. I think you should use the following instead of that line.
String string = sc.nextLine();
If you just want to remove the beginning and ending whitespace, you can use the built in function trim(), e.g. " abcd ".trim() is "abcd"
If you want to remove it everywhere, you can use the replaceAll() method with the whitespace class as the parameter, e.g. " abcd ".replaceAll("\W","").
Use a StringTokenizer to remove " "
StringTokenizer st = new StringTokenizer(string," ",false);
String t="";
while (st.hasMoreElements()) t += st.nextElement();
String result = t;
System.out.println(result);
I haven't actually tesed this, but have you considered the String.replaceAll(String regex, String replacement) method?
public static String removeJunk (String string) {
return string.replaceAll (" ", "");
}
Another thing to look out for is that while removing all non-digit/alpha characters removeJunk also reverses the string (it starts from the end and then appends one character at a time).
So after reversing it again (in reverse) you are left with the original and it will always claim that the given string is a palindrome.
You should use the String replace(char oldChar, char newChar) method.
Although the name suggests that only the first occurrence will be replaced, fact is that all occurrences will be replaced. The advantage of this method is that it won't use regular expressions, thus is more efficient.
So give a try to string.replace(' ', '');
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()