Convert sentence to variable name syntax [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How would I convert a String from something like "Bobs big barbeque" to bobsBigBarbeque?
String variableName = result;
for ( int i = 0; i < result.length( ); i++ ) {
char c = result.charAt( i );
if ( c == ' ' ) {
Character.toUpperCase( variableName.charAt( result.indexOf( c )+1 ) );
}
variableName = variableName.replace( " ", "" );
Character.toLowerCase( variableName.charAt( 0 ) );
System.out.println( variableName );
}
I almost have it working. My only problem now is with the line....
Character.toLowerCase( variableName.charAt( 0 ) );
I have to just convert the first character to lowercase

String str = "Bobs big barbeque";
str = str.replace(" ", "");
If you only want to replace space from given string try above code:
I wrote code below based on your given input and output:
public static void main(String[] args) {
String str = "Bobs big barbeque";
String newStr = String.valueOf(str.charAt(0)).toLowerCase();
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
newStr = newStr
+ String.valueOf(str.charAt(i + 1)).toUpperCase();
i = i + 1;
}
newStr = newStr + String.valueOf(str.charAt(i));
}
System.out.println(newStr);
}

String sentence = "Bobs big barbeque";
String[] words = sentence.split(" ");
String newVarName = "";
for (int i = 0; i < words.length; i++) {
if (i == 0) {
newVarName += words[i].toLowerCase();
} else {
newVarName += words[i].substring(0,1).toUpperCase() + words[i].substring(1);
}
}
You'll probably want to take the time to make it more secure by making sure the substrings don't overflow but essentially it takes your sentence, breaks it apart on spaces then reconstructs it by making the first word lowercase and all others start with a capital.
EDIT: Fixed my string function names... alternatively you could do this which I think looks cleaner:
for (int i = 0; i < words.length; i++) {
newVarName += words[i].substring(0,1).toUpperCase() + words[i].substring(1);
}
newVarName = newVarName.substring(0,1).toLowerCase() + newVarName.substring(1);

String a = "Bobs big barbeque";
a = WordUtils.capitalizeFully(a); //Capitalize the first letter of each word only
a = a.replace(" ", ""); // Remove Spaces
a = a.substring(0,1).toLowerCase() + a.substring(1); // Lowercase first letter
Note: or just capitalize(a) to capitalize the first letter of each word, and leave the rest of the word alone. E.g.
BoBs bIg barBeque would be BoBs BIg BarBeque with capitalize(a)
Bobs Big Barbeque with capitlizeFully(a);

String a = "Bobs big barbeque";
String r = a.replace(" ","");
r now contains your string without spaces...

Related

Pallindrome String is replaced by * character [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Input a string which contains some palindrome substrings. Find out the position of palindrome substrings if exist and replace it by *. (For example if input string is “bob has a radar plane” then it should convert in “** has a ***** plane”.
My code is given below.
import java.util.Scanner;
public class Pallindrome_String {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String sen;
System.out.println("Enter the String: ");
sen = in.nextLine();
pallindrome(sen);
in.close();
}
public static void pallindrome(String s) {
int len = s.length();
for (int i = 0; i < len; i++) {
String res = "";
if (s.charAt(i) == ' ') {
res = s.substring(0, i);
String rev = "";
for (int j = res.length() - 1; j >= 0; j--) {
rev = rev + res.charAt(i);
}
if (rev.equals(res)) {
rev = "*";
System.out.print(rev + " ");
} else {
System.out.print(res + " ");
}
}
}
}
}
There is a simpler, more efficient way of finding palindromes in Java. I'll explain the steps to implementing it.
first, after getting your input 'sen', you can use the split method of the String class to seperate each word.
sen = in.nextLine();
String[] splitted = s.split(" "); // seperates the string when there is a whitespace and stores the resulting words in an array
After you've got the words in an array, you can check each word and see if its a palindrome. To do so, you can read the word front to back and back to front and compare the result.
If u find a palindrome, store its index (position in the 'splitted' array). After you've gone through all the words in the 'splitted' array, you can then print out the appropriate number of *'s based on the length of the word.
The split() will loose double spaces and punctuation in source string and make a lot of useless objects in memory. This is more correct solution. IMHO
public static void main(String[] args) {
String s = "Bob! Do you have a radar plane?";
StringBuilder sb = new StringBuilder(s);
Matcher m = Pattern.compile("[a-zA-Z]+").matcher(s);
while (m.find()) {
String word = m.group();
if (word.length() == 0)
continue;
String reversed = new StringBuffer(word).reverse().toString();
if (word.equalsIgnoreCase(reversed)) {
StringBuilder replacement = new StringBuilder();
for (int i = 0; i < word.length(); i++)
replacement.append('*');
sb.replace(m.start(), m.end(), replacement.toString());
}
}
System.out.println(sb);
}

Java: How to turn a text file with string in format {i,j},{i,j},{i,j} into a 2-dimensional array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
My text file is as follows :
{11-11,22},{33-33,44},...{88-88,99}
How can I turn this into a 2 dimensional array in Java in the form:
[[11-11,22],[33-33,44],...[88-88,99]]
Solution:
String source = "{11-11,22},{33-33,44},{88-88,99}";
String[] splittedSource = source.split("(?<=\\}),(?=\\{)");
Pattern p = Pattern.compile("\\{([^,]+),([^\\}]+)");
String[][] result = new String[splittedSource.length][2];
for(int i = 0; i < splittedSource.length; i++) {
Matcher m = p.matcher(splittedSource[i]);
while(m.find()) {
result[i][0] = m.group(1);
result[i][1] = m.group(2);
System.out.print(m.group(1) + " " + m.group(2) + "\n");
}
}
System.out.println(Arrays.deepToString(result));
Explanation:
source.split("(?<=\\}),(?=\\{)"); - splitting source on ',' character preceded by '}' and followed by '{'
Pattern.compile("\\{([^,]+),([^\\}]+)"); - two capturing groups in parenthesis "()", first contains all characters other than ',' until it reaches ',', second contains all characters after the ',' except '}'
new String[splittedSource.length][2]; - it's [3][2] in this example
Matcher m = p.matcher(splittedSource[i]); - here you say that you will check given pattern against each element from splittedSource[]
Output you get from this code:
11-11 22
33-33 44
88-88 99
[[11-11, 22], [33-33, 44], [88-88, 99]]
public static void main(String[] args) {
Scanner in = new Scanner(Thread.currentThread().getContextClassLoader().
getResourceAsStream("input/test.txt"));
String line = in.nextLine();
String[] tokens = line.split("},");
String[][] finalArray = new String[tokens.length][2];
for (int i = 0; i < tokens.length; i++) {
tokens[i] = tokens[i].replace("{", "");
tokens[i] = tokens[i].replace("}", "");
finalArray[i] = tokens[i].split(",");
}
for (int i = 0; i < finalArray.length; i++) {
System.out.println(Arrays.toString(finalArray[i]));
}
}

How to add spaces in between numbers contained inside a string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have string as "DOC_87654321 -ABC76543". What I want is add spaces in between numbers. The result should be "DOC_8 7 6 5 4 3 2 1-ABC7 6 5 4 3". How can it possible?
Try this
String str = "DOC_87654321 -ABC76543";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isDigit(c)) {
sb.append(c + " ");
} else {
sb.append(c);
}
}
Log.e("DATA",sb.toString());
you can use this:
String str = "DOC_87654321 -ABC76543- 959565412";
String finalStr = "";
String[] split = str.split("-");
for (int i = 0; i < split.length; i++) {
finalStr +=
split[i]
.replaceAll("([0-9])", "$1 ")
.trim()
+ (i != split.length - 1 ? '-' : "");
}
System.out.println("finalStr = " + finalStr);
In case if you don't wanna use Character.isDigit() you can compare their ascii decimal values and use it like this
public static void main(String[] args) {
String str = "DOC_87654321 -ABC76543";
StringBuilder string = new StringBuilder();
for(int i=0;i<str.length();i++) {
if(str.charAt(i) >= 48 && str.charAt(i) <=57) {
string.append(str.charAt(i)+" ");
}else {
string.append(str.charAt(i));
}
}
System.out.println(string.toString());
}

Recursively computing all possible permutations of a string Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to compute all possible permutations of a given string using recursion in Java. However, I don't know what's wrong with my code.
Here's my algorithm:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
//base case
if (str.length() == 1)
perms.add(str);
else {
//loop over the string
for (int i = 0; i < str.length() - 1; i++) {
//make a subset of the string excluding the first char
String sub = str.substring(i + 1, str.length());
//compute permutations of the subset
ArrayList<String> subPerms = computeAllPossiblePermutations(sub);
//add the first char that we excluded at the start of each permutations
for (String s : subPerms) {
s = str.charAt(i) + s;
perms.add(s);
}
}
}
return perms;
}
There are a few issues:
The following line: String sub = str.substring(i+1, str.length()); ignores the first character
The same line also treats anything after index i as a "block" of substring that is left unchanged, while in order to generate permutation we should insert the current (first) character in between any two characters of the rest of the string - and do that for each permutation
The line s = str.charAt(i) + s; repeats the same mistake in #2
Here's a suggested fix:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
if (str.length() == 1) {
perms.add(str);
} else {
String chr = str.substring(0,1);
String rest = str.substring(1);
ArrayList<String> subPerms = computeAllPossiblePermutations(rest);
for (String s : subPerms) {
for (int j = 0; j <= s.length(); j++) {
String newPerm = s.substring(0,j) + chr + s.substring(j);
perms.add(newPerm);
}
}
}
return perms;
}

Accessing The Character Right after a blank space [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to access character right after a blank space and convert it into Capital.
I know capitalizing and removing blank space but can't access the character after a space.
I want to convert: "File to be uploaded" to "FileToBeUploaded".
Without Regex
First thing to do would be to split on " "..
String[] tokens = string.split(" ");
Then the next step is to cycle through each token, and grab the first letter.
for(int x = 0; x < tokens.length; x++)
{
String token = tokens[x];
String firstLetter = String.valueOf(tokens[x].charAt(0));
// After you have first letter, it's just a case of moving to upper case..
firstLetter = firstLetter.toUpperCase();
tokens[x] = firstLetter + tokens[x].substring(1, tokens[x].length());
}
Note: I didn't use a foreach loop because a foreach will only read.
Finally, stick it all together. You can do this in the same loop. If you don't want to change the array itself, you can use a foreach in this context, which will look nicer; as follows:
StringBuilder sb = new StringBuilder();
// Use a string builder for string creation.
for(String token : tokens)
{
String firstLetter = String.valueOf(token.charAt(0));
// After you have first letter, it's just a case of moving to upper case..
firstLetter = firstLetter.toUpperCase();
sb.append(firstLetter + token.substring(1, token.length()););
}
System.out.println(sb.toString());
Try this
String str = "File to be uploaded";
String[] arr = str.split(" ");
StringBuilder sb = new StringBuilder();
for (String i : arr) {
sb.append(i.substring(0, 1).toUpperCase() + i.substring(1, i.length()));
}
System.out.println(sb.toString());
// With regex it is very simple
private String capitalEachWord(String s) {
Pattern p = Pattern.compile("\\s+\\w"); // Search for one or more space
Matcher m = p.matcher(s);
StringBuffer buffer = new StringBuffer();
while (m.find()) m.appendReplacement(buffer, m.group().toUpperCase());
m.appendTail(buffer); // add to last
return buffer.toString();
}
This form of a string is called CamelCase.
As you can't change the characters in a string (since it's immutable), you have to build a new String by iterating over the characters. If you encounter a white space, skip that character but remember to capitalize the next.
public static String toCamelCase (String s) {
StringBuilder builder = new StringBuilder();
boolean capitalizeNextChar = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isWhitespace(c)) {
capitalizeNextChar = true;
} else {
if (capitalizeNextChar) {
c = Character.toUpperCase(c);
capitalizeNextChar = false;
}
builder.append(c);
}
}
return builder.toString();
}
Simply you can also use split()
String abc = "File to be uploaded";
String temp[] = abc.split(" ");
String Result = "";
for (int i = 0; i < temp.length; i++)
{
if (temp[i].length() > 0)
Result = Result + temp[i].substring(0, 1).toUpperCase() + temp[i].substring(1, temp[i].length());
}
System.out.println(Result);
Output:
FileToBeUploaded

Categories

Resources