I am using StringBuilder in my project. When I appen char everything is OK, but when I try to append string "8 (" or ") " or " ", it stays empty "".
Example (EDITED):
int length = number.length();
CharSequence sequence = number.subSequence(0,length);
StringBuilder stringBuilder = new StringBuilder(17);
for (int i = 0; i < length; i++){
if (Pattern.matches("^[\\d]$", String.valueOf(sequence.charAt(i)))){
stringBuilder.append(sequence.charAt(i));
}
}
sequence = stringBuilder.toString();
stringBuilder = new StringBuilder(17);
CharSequence s = "8 (";
if (sequence.charAt(0) == 8 || sequence.charAt(0) == 7 || sequence.length() == 0){
stringBuilder.append(s);
}
for (int i = 1; i < 11 && i < sequence.length(); i++){
stringBuilder.append(sequence.charAt(i));
if (i == 3){
stringBuilder.append(") ");
}
if (i == 6 || i == 8){
stringBuilder.append(' ');
}
}
number.clear();
number.clearSpans();
number.append(stringBuilder.toString());
The problem with your code is
if (sequence.charAt(0) == 8 || sequence.charAt(0) == 7 ||
you need to compare to chars not ints
if (sequence.charAt(0) == '8' || etc
Related
I want to find vowels positions in the string. How can I make shorter this code?
I tried contains and indexOf method but couldn't do it.
String inputStr = "Merhaba";
ArrayList<Character> vowelsBin = new ArrayList<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
ArrayList<Integer> vowelsPos = new ArrayList<Integer>();
for (int inputPos = 0; inputPos < inputStr.length(); inputPos = inputPos + 1)
for (int vowelPos = 0; vowelPos < vowelsBin.size(); vowelPos = vowelPos + 1)
if (inputStr.charAt(inputPos) == vowelsBin.get(vowelPos)) vowelsPos.add(inputPos);
return vowelsPos;
I assume you want to get m2rh5b7 from your input string Merhaba based on your code, then the below works fine,
String input = "Merhaba";
StringBuilder output = new StringBuilder();
for(int i = 0; i < input.length(); i++){
char c = input.toLowerCase().charAt(i);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
output.append(i+1);
} else {
output.append(c);
}
}
System.out.println(output); // prints --> m2rh5b7
Or if you want just position of the vowels position only, the below is fine,
String input = "Merhaba";
for(int i = 0; i < input.length(); i++){
char c = input.toLowerCase().charAt(i);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
System.out.println(i);
}
}
you can use regex also, please refer the above from Alias.
I want to repeat only the words in my input string. But the order of output is not right. Here's my code:
public static String repeatWords(String s, int num){
StringBuilder sb = new StringBuilder();
StringBuilder sbtemporary = new StringBuilder();
int leng = s.length();
for (int i=0; i < leng; i++){
char c = s.charAt(i);
int b = (int) c;
if (b >= 65 && b <= 90 || b >= 97 && b <= 122){
sbtemporary.append(c);
} else if (b == 32){
sbtemporary.append(" ");
}
if (b == 32){
for (int j = 1; j<= num-1; j++){
sb = sb.append(" " + sbtemporary);
sbtemporary.delete(0,sbtemporary.length());
}
}
sb.append(c);
}
String str = sb.toString();
return str;
}
s is the input string, num is the times that needs to repeat. The result I want is like :
When the input is : "How are you? I am fine."
The output should be like: "How How are are you you?"
But the result of my code is:
"How How are are you? you I I am am fine."
I don't really know where goes wrong, pls could someone help me with this?
System.out.println((int) "?".charAt(0)); //63
System.out.println((int) ".".charAt(0)); //46
"?" and "." do not append to sbtemporary.
Corrected Code:-
public static String repeatWords(String s, int num){
StringBuilder sb = new StringBuilder();
StringBuilder sbtemporary = new StringBuilder();
int leng = s.length();
for (int i=0; i < leng; i++){
char c = s.charAt(i);
int b = (int) c;
if (b >= 65 && b <= 90 || b >= 97 && b <= 122){
sbtemporary.append(c);
}
if (b == 32 && sbtemporary.length() != 0){
for (int j = 1; j<= num-1; j++){
sb.append(" " + sbtemporary);
}
sbtemporary.delete(0,sbtemporary.length());
}
sb.append(c);
}
String str = sb.toString();
return str;
}
Changes:-
Removed the else if (b == 32) part where you are appending space to sbtemporary.
Delete content of sbtemporary outside the j loop, else it will work only for num == 2.
And in the if condition b == 32 added one more condition if sbtemporary is not empty.
Add this checking, and add to sbtemporary for the repeated part.
System.out.println(repeatWords(str, 1));
if ( b == 63) {
sb = sb.append(" " + sbtemporary);
sb.append(c);
break;
}
if (b == 63) {
for (int j = 1; j<= num; j++){
sb.append(" " + sbtemporary);
}
sb.append(c);
break;
}
public static String repeatWords(String s, int num) {
StringBuilder sb = new StringBuilder();
StringBuilder sbtemporary = new StringBuilder();
int leng = s.length();
for (int i = 0; i < leng; i++) {
char c = s.charAt(i);
int b = (int) c;
if (b == 63) {
for (int j = 1; j<= num; j++){
sb.append(" " + sbtemporary);
}
sb.append(c);
break;
}
if (b >= 65 && b <= 90 || b >= 97 && b <= 122) {
sbtemporary.append(c);
}
if (b == 32 && sbtemporary.length() != 0){
for (int j = 1; j<= num; j++){
sb.append(" " + sbtemporary);
}
sbtemporary.delete(0,sbtemporary.length());
}
sb.append(c);
}
String str = sb.toString();
return str;
}
You can simply do this instead,
String content = "How are you? I am fine.";
String[] words = content.split("\\s"); // `\\s` preserves any 2 or more repeated spaces
StringBuilder builder = new StringBuilder();
for(String word : words) {
for(int i = 0; i < n; i++) { // n is the no. of times to repeat the word
builder.append(word).append(" ");
}
}
System.out.printf("Repeated String : %s", builder.toString().trim());
A more tidy way with Java8, here Collections.nCopies(n, word) simply returns you a list of the word repeated n times, which is converted in a single String separated by space, and eventually, all such repeated strings are converted in one finally resultant string separated by space.
String content = "How are you? I am fine.";
String[] words = content.split("\\s");
String result = Arrays.stream(words)
.map(word -> String.join(" ", Collections.nCopies(n, word)))
.collect(Collectors.joining(" ")); //n is the no. of times to repeat the word
System.out.printf("Repeated String : %s", result);
I'm trying to solve this problem
https://vjudge.net/problem/UVALive-6805
I found solution but in c++ , Can anybody help me converting it to java code. I'm very newbie to programming
I tried a lot of solutions but non of them work.
Please I need help in this if possible
I don't know for example what is the equivalent for .erase function in c++ in java
Also is is sbstr in c++ provide different result from java ?
#include <iostream>
#include <string>
using namespace std;
int syllable(string word)
{
int L = word.size();
int syllable;
if (L>=7)
{
syllable = 3;
}
else if (L==6)
{
int indicator = 0;
for (int k=0; k<=L-2; k++)
{
string subword = word.substr(k, 2);
if (subword == "ng" || subword == "ny")
{
indicator++;
}
}
if (indicator == 0)
{
syllable = 3;
}
else
{
syllable = 2;
}
}
else if (L == 4 || L == 5)
{
syllable = 2;
}
else if (L == 3)
{
char Char = word[0];
if (Char=='a' || Char=='A' || Char=='e' || Char=='E' || Char=='i' || Char=='I' || Char=='o' || Char=='O' || Char=='u' || Char=='U')
{
syllable = 2;
}
else
{
syllable = 1;
}
}
else
{
syllable = 1;
}
return syllable;
}
int main()
{
string word;
int T;
cin >> T;
for (int i=1; i<=T; i++)
{
int syl[] = {0, -1, -2, -3};
string rhy[] = {"a", "b", "c", "d"};
int verse = 0;
int stop = 0;
while (stop == 0)
{
cin >> word;
int L = word.size();
char end = word[L-1];
if (end == '.')
{
stop = 1;
}
if (word[L-1] == ',' || word[L-1] == '.')
{
word = word.erase(L-1, 1);
L = word.size();
}
if (verse<=3)
{
syl[verse] = syl[verse] + syllable(word);
}
if (end == ',' || end == '.')
{
if (verse<=3)
{
rhy[verse] = word.substr(L-2, 2);
}
verse++;
if (verse<=3)
{
syl[verse] = 0;
}
}
}
int A = 0, B = 0, C = 0, D = 0;
for (int k=0; k<4; k++)
{
if (syl[k] >= 8 && syl[k] <= 12)
{
A = A + 10;
}
}
for (int k=0; k<2; k++)
{
if (rhy[k] == rhy[k+2])
{
B = B + 20;
}
}
for (int k=0; k<2; k++)
{
if (syl[k] == syl[k+2])
{
C = C + 10;
}
}
if (verse > 4)
{
D = (verse - 4) * 10;
}
int E = A + B + C - D;
cout << "Case #" << i << ": " << A << " " << B << " " << C << " " << D << " " << E << endl;
}
}
here is my trying
import java.util.*;
public class First {
public static int syllable(String word) {
int L = word.length();
int syllable;
if (L >= 7) {
syllable = 3;
} else if (L == 6) {
int indicator = 0;
for (int k = 0; k < L - 3; k++) {
String subword = word.substring(k, 2);
if (subword == "ng" || subword == "ny") {
indicator++;
}
}
if (indicator == 0) {
syllable = 3;
} else {
syllable = 2;
}
} else if (L == 4 || L == 5) {
syllable = 2;
} else if (L == 3) {
char Char = word.charAt(0);
if (Char == 'a' || Char == 'A' || Char == 'e' || Char == 'E' || Char == 'i' || Char == 'I' || Char == 'o'
|| Char == 'O' || Char == 'u' || Char == 'U') {
syllable = 2;
} else {
syllable = 1;
}
} else {
syllable = 1;
}
return syllable;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word;
int T;
T = sc.nextInt();
for (int i = 1; i <= T; i++) {
int syl[] = { 0, -1, -2, -3 };
String rhy[] = { "a", "b", "c", "d" };
int verse = 0;
int stop = 0;
while (stop == 0) {
word = sc.next();
int L = word.length();
char end = word.charAt(L-1);
if (end == '.') {
stop = 1;
}
if (word.charAt(L-1) == ',' || word.charAt(L-1) == '.') {
word.substring(L-1, 1);
L = word.length();
}
if (verse <= 3) {
syl[verse] = syl[verse] + syllable(word);
}
if (end == ',' || end == '.') {
if (verse <= 3) {
rhy[verse] = word.substring(L - 2, 2);
}
verse++;
if (verse <= 3) {
syl[verse] = 0;
}
}
}
int A = 0, B = 0, C = 0, D = 0;
for (int k = 0; k < 4; k++) {
if (syl[k] >= 8 && syl[k] <= 12) {
A = A + 10;
}
}
for (int k = 0; k < 2; k++) {
if (rhy[k] == rhy[k + 2]) {
B = B + 20;
}
}
for (int k = 0; k < 2; k++) {
if (syl[k] == syl[k + 2]) {
C = C + 10;
}
}
if (verse > 4) {
D = (verse - 4) * 10;
}
int E = A + B + C - D;
System.out.println("Case #" + i + ": " + A + " " + B + " " + C + " " + D + " " + E);
}
}
}
The Exception is thrown by your second and your third call of String substring method. Your beginIndex is higher than your endIndex. As you can see in here https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int) beginIndex always has to be lower than the endIndex.
Before answering your question, there are some important points to mention in regards to Strings and Java in general.
Strings are immutable (This also applies to C++). This means that no method called on a String will change it, and that all methods simply return new versions of the original String with the operations done on it
The substring method in java has two forms.
One takes in beginIndex and returns everything from beginIndex to str.length() - 1 (where str represents a String)
The other takes in the beginIndex, and the endIndex, and returns everything from beginIndex to endIndex - 1. The beginIndex should never be larger than endIndex otherwise it throws an IndexOutOfBoundsException
C++'s substring method (string::substr()) takes in the beginning "index" and takes in the number of characters after it to include in the substring. So by doing substr(L-2, 2) you get the last two characters of the string.
Java will never allow you to go out of bounds. That means you need to constantly check whether you are within the bounds of anything you are iterating through.
With all this in mind, I would go and verify that all of the substring() method calls are returning the proper range of characters, and that you are properly reassigning the values returned from substring() to the proper variable.
To mimic C++'s string::erase(), depending on what part of the word you want to erase, you want to get the substring of the part before and the substring of the part after it and add them together.
Ex. Lets say I have a String line = "I do not like the movies"; Since it is impossible for anyone to not like movies, we want to cut out the word not
We do this by doing what I said above
String before = line.substring(0, 5); // This gives us "I do " since it goes up to but not including the 5th index.
String after = line.substring(5 + 3); // This gives us the rest of the string starting after the word "not" because not is 3 characters long and this skips to the 3rd index after index 5 (or index 8)
line = before + after; // This'll add those two Strings together and give you "I do like the movies"
Hope this helps!
I have a String of a length of more than 1000 character. In this string i have to print 1st character after that every 5th character.
I tried writing a program to iterate from 0th character to last character and have a count variable.
If count is equal to 5. I am printing the character and count is initializing with 0.
private static String getMaskedToken(String token) {
if (token == null)
return null;
char[] charArray = token.toCharArray();
int length = token.length();
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < length; i++) {
count++;
if (i == 0 || i == length - 1) {
sb.append(charArray[i]);
} else if (count == 5) {
sb.append(charArray[i]);
count=0;
} else if(count < 5 && i == length-1){
sb.append(charArray[i]);
}else {
sb.append('*');
}
}
return sb.toString();
}
Need to print last character if count is less than 5 of last
iteration.
If String of length 9, "12345678" then actual output will be like
1***5**8
If String of length 9, "123456789abcd" then actual output will be
like 1***5****a**d
String output = "";
for (int i = 0; i < str.length(); i++) {
if (i == 0) {
output += str.charAt(i);
output += "***";
output += str.charAt(4);
i = 4;
} else if ((i - 4) % 5 == 0) {
output += str.charAt(i);
} else if (i == str.length()-1) {
output += str.charAt(i);
} else {
output += "*";
}
}
System.out.println(output);
}
This will print 1***5****a**d for string "123456789abcd".
try this code:
public void printFirstAndEveryFifthCharecter(String str)
{
for (int i = 0 ; i < str.length() ; i++)
{
if ((i+1) == 1 | (i+1) % 5 == 0) {
System.out.print(str.charAt(i) + "***");
}
}
if (str.length() % 5 > 0) {
System.out.print(str.charAt(str.length() - 1));
}
}
Your code should work fine. Here's an alternative without using StringBuilder and with fewer checks.
private static String getFirstFifthLast(String str) {
String[] strArray = str.split(""); //returns an array of strings with length 1
int arrayLength = strArray.length;
String result = strArray[0]; //append the first element
//append element if it is in 5th position, append "*" otherwise
for (int i = 0; i < arrayLength; i++) {
if ((i + 1) % 5 == 0) {
result += strArray[i];
} else {
result += "*";
}
}
result += strArray[arrayLength - 1]; //append the last element
return result;
}
Try this code,
private void printEvery5thCharacter(String str) {
for (int i = 1; i < str.length() - 1; i += 5) {
System.out.print(str.charAt(i - 1) + "***");
if (i == 1) {
i = 0;
}
}
if (str.length() % 5 > 0) {
System.out.print(str.charAt(str.length() - 1));
}
}
My program is working fine, in terms of output, but for some of my test cases it takes too long to find an answer (sometimes taking 18 seconds). I would like to know how I can improve the performance of my code.
What my code does:
It's a take on Pebble Solitaire. The user inputs n number of games and after that inputs a strings of length 23 that contains a combinations of only 'o' (pebble) and '-' (empty space). If there are 2 adjacent pebbles and an empty space on either side, ie (oo- OR -oo), then you remove the middle pebble and you swap other two pieces with each other, ex 'oo-' will turn into '--o'.
My current approach is pretty much an exhaustive approach where it tries out every possible move and results the move set with the least number of pebbles left.
I would like to know how I can improve this solution without making it multi-threaded.
Here is what I have:
package Pebble;
import java.util.Scanner;
public class PebbleSolitaire {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int numOfGames = Integer.parseInt(input.nextLine());
while (numOfGames > 0){
char[] values = input.nextLine().toCharArray();
long startTime = System.nanoTime();
System.out.println(solve(values));
System.out.println("Time to finish in ms: " + (System.nanoTime() - startTime) / 1000000);
numOfGames--;
}
input.close();
}
private static int solve(char[] game){
if(game != null && game.length == 0){
return -1;
}
int result = 0;
for (int i = 0; i < game.length; i++){
if(game[i] == 'o'){
result++;
}
}
//print(game);
for (int i = 0; i < game.length; i++ ){
char[] temp = new char[game.length];
copyArray(temp, game);
if (i-2 >= 0 && temp[i] == '-' && temp[i-2] == 'o' && temp[i-1] == 'o'){//move pebble forwards
temp[i-1] = temp[i-2] = '-';
temp[i] = 'o';
result = Math.min(result, solve(temp));
}
copyArray(temp, game);
if(i+2 < temp.length && temp[i] == '-' && temp[i+1] == 'o' && temp[i+2] == 'o'){//move pebble backwards
temp[i+1] = temp[i+2] = '-';
temp[i] = 'o';
result = Math.min(result, solve(temp));
}
}
return result;
}
private static void copyArray(char[] copy, char[] og){
for(int x = 0; x < copy.length; x++){
copy[x] = og[x];
}
}
private static void print(char[] c){
for(char ch: c){
System.out.print(ch);
}
System.out.println();
}
}
My sample input and output:
2
-o----ooo----o----ooo--
6
Time to finish in ms: 0
oooooooooo-ooooooooooo-
4
Time to finish in ms: 18149
EDIT: Would making this completely iterative drastically improve the performance?
Maybe you can improve this parte:
for (int i = 0; i < game.length; i++ ){
char[] temp = new char[game.length];
copyArray(temp, game);
if (i-2 >= 0 && temp[i] == '-' && temp[i-2] == 'o' && temp[i-1] == 'o'){//move pebble forwards
temp[i-1] = temp[i-2] = '-';
temp[i] = 'o';
result = Math.min(result, solve(temp));
}
copyArray(temp, game);
if(i+2 < temp.length && temp[i] == '-' && temp[i+1] == 'o' && temp[i+2] == 'o'){//move pebble backwards
temp[i+1] = temp[i+2] = '-';
temp[i] = 'o';
result = Math.min(result, solve(temp));
}
}
to:
for (int i = 0; i < game.length; i++ ){
char[] temp = null;
if (i-2 >= 0 && game[i] == '-' && game[i-2] == 'o' && game[i-1] == 'o'){//move pebble forwards
temp = new char[game.length];
copyArray(temp, game);
temp[i-1] = temp[i-2] = '-';
temp[i] = 'o';
result = Math.min(result, solve(temp));
}
if(i+2 < game.length && game[i] == '-' && game[i+1] == 'o' && game[i+2] == 'o'){//move pebble backwards
if(temp == null) temp = new char[game.length];
copyArray(temp, game);
temp[i+1] = temp[i+2] = '-';
temp[i] = 'o';
result = Math.min(result, solve(temp));
}
}
Basically, only creating and "copyArray(temp, game);" when strictly necessary.