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());
}
Related
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
Got a String like:
String str = "###############";
Got guess word, for example:
String guess = "Java"
User must guess word:
User input:
Sava
Sring should be:
String str = "#a#a###########";
all right symbols placed on their indexes
String is immutable class.
I chose Stringbuilder
for (int i = 0; i < length ; i++) {
if (rnd.charAt(i) == guess.charAt(i) && rnd.charAt(i) != '#'){
sb.append(rnd.charAt(i));
}
}
System.out.println(sb);
sb.delete(0, sb.length());
Stringbuilder add right symbols not on possition 'i', but on the last indexes.
Example:
guess word: Java
user input Sala:
System.out.println(sb);
###############aa
How I can achieve needed result?
And what tools should I use?
needed result:
Example:
guess word Java:
user input Sala:
System.out.println(sb);
#a#a###########
Work like this:
private static String word(){
String guess = new Scanner(System.in).nextLine();
return guess;
}
private static void guessWord(String[]arr) {
int random = new Random().nextInt(arr.length);
String rnd = arr[random];
int length = 15;
StringBuilder sb = new StringBuilder();
String guess = "";
int rndLength = length - rnd.length();
int guessLength = length - guess.length();
do {
System.out.println("Enter a word: ");
guess = word();
if (sb.length() < length){
for (int i = 0; i < length ; i++) {
sb.append("#");
}
}
for (int i = 0; i < length && i < rnd.length() && i < guess.length(); i++) {
if (rnd.charAt(i) == guess.charAt(i)){
sb.setCharAt(i, rnd.charAt(i));
sb.delete(length, sb.length());
}
}
if (rnd.equals(guess)){
System.out.println("Guess word: " + rnd);
break;
}else if (!rnd.equals(guess)) {
System.out.println(sb);
}
}while (!rnd.equals(guess));
}
You can do it as follows:
public class Main {
public static void main(String[] args) {
String str = "#a#a###########";
String guess = "Java";
String input = "Sala";
StringBuilder sb = new StringBuilder();
int i;
for (i = 0; i < str.length() && i < guess.length() && i < input.length(); i++) {
// In case of a match, append the matched character
if (guess.charAt(i) == input.charAt(i)) {
sb.append(guess.charAt(i));
} else {// Else append the placeholder symbol from `str`
sb.append(str.charAt(i));
}
}
// Append the remaining placeholder characters from `str`
sb.append(str.substring(i));
// Display
System.out.println(sb);
}
}
Output:
#a#a###########
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]));
}
}
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;
}
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 8 years ago.
Improve this question
Does anyone know if there is another method other than WordUtils.capitalize() that converts the first letter of each word to upper case?
You could use a method you create:
String CapsFirst(String str) {
String[] words = str.split(" ");
StringBuilder ret = new StringBuilder();
for(int i = 0; i < words.length; i++) {
ret.append(Character.toUpperCase(words[i].charAt(0)));
ret.append(words[i].substring(1));
if(i < words.length - 1) {
ret.append(' ');
}
}
return ret.toString();
}
public static String caseFirst(String givenString) {
String[] a= givenString.split(" ");
StringBuffer s= new StringBuffer();
for (int i = 0; i < a.length; i++) {
s.append(Character.toUpperCase(a[i].charAt(0))).append(a[i].substring(1)).append(" ");
}
return s.toString().trim();
}
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...