Multiply single character by given number in String - java

I have one goal:
1) Multiply character in String n-times (character, String, n [int] - from user input)
Example:
User input1 (String) : future
User input2 (char) : u
User input3 (int) : 2
Output: fuutuure
First i tried with char[] array but IndexOutOfBoundsException brought me back to reality. Second try-StringBuilder but its not working aswell-empty result window. Should I use StringBuilder (and if answer is yes-how?) ? Or there is other, better solution.
Thank you for help.
package Basics.Strings;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Ex4 {
static String giveAWord() {
Scanner scanWord = new Scanner(System.in);
System.out.println("Give a word");
String word = scanWord.nextLine();
return word;
}
static char giveALetter() {
Scanner scanALetter = new Scanner(System.in);
System.out.println("Give a letter");
char let = scanALetter.next().charAt(0);
return let;
}
static int giveANumber() {
Scanner scanNumber = new Scanner(System.in);
System.out.println("Give a number");
int numb = scanNumber.nextInt();
return numb;
}
static String multiplyLetter(String word, char letter, int number) {
StringBuilder sb= new StringBuilder();
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i)==letter) {
sb.append(i*number);
}
}
return sb.toString();
}
public static void main(String[] args) {
String word = giveAWord();
char letter = giveALetter();
int number = giveANumber();
System.out.println(multiplyLetter(word, letter, number));
}
}

There are several things in your multiplyLetter method that would make it not work.
First, you have to initialise the StringBuilder using the word so:
StringBuilder sb = new StringBuilder(word) ;
Else, your StringBuilder will be empty.
Second, you should use the insert(int pos, char c) method, so you can specify where you want tthe character inserted.
And last, you can't just multiply a char and an int and get away with it. If you want to repeatedly insert a character, I think you should use a loop.
So, in summary, try:
StringBuilder sb= new StringBuilder(word);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i)==letter) {
for ( int j = 0 ; j < number ; j++ ) {
sb.insert(i, letter);
i++ ;
}
}
}
Notice I added i++ inside the loop, as sb.length() will increase with each character inserted.
Also, maybe someone more experienced can provide with a more efficient way than just using a loop.

If you are using at least Java 11 (eleven) then the following will work:
String word = "future";
String letter = "u";
int count = 2;
String replacement = letter.repeat(count);
String result = word.replace(letter, replacement);
Note that only method repeat(int) was added in Java 11.
Method replace(CharSequence, CharSequence) was added in Java 5

Java 8 functional way:
String alterString(String input, Character charMatch, int times) {
return input.chars()
.mapToObj(c -> (Character) c) // converting int to char
.flatMap(c -> {
if (c == charMatch) {
Character[] ca = new Character[times];
Arrays.fill(ca, c);
return Arrays.stream(ca); // stream of char c repeated 'times' times
}
return Stream.of(c);
})
.collect(
// following is the string collecting using StringBuilder form stream of characters
Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString,
);
);
}

A simple way to solve this problem is by using the following functions:
String#join
Collections#nCopies
String#replace
Demo:
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = kb.nextLine();
System.out.print("Enter the character: ");
String ch = kb.nextLine();
System.out.print("How many times to repeat?: ");
int n = kb.nextInt();
String result = str.replace(ch, String.join("", Collections.nCopies(n, ch)));
System.out.println("Result: " + result);
}
}
A sample run:
Enter the string: future
Enter the character: u
How many times to repeat?: 2
Result: fuutuure

Related

Reducing and printing a string Array

I am trying to reduce the string array by using a for a loop. This is an example I tried to do
User string input: Calculus
User input:5
output: CalcuCalcCalCaC
I have turned the string to a char array but the issue presents itself when trying to print them out multiple times. It only prints once and has the right starting output.
input string: Oregon
input number: 4
output: Oreg
I notice my for loop says that it is not looping when I hover over it on the IDE that I downloaded from JetBrains.
I tried different combinations of decrementing and incrementing but could not get that "for statement is not looping". Other than that I have tried different ways to do something in the for loop but I don't think anything needs to be done for now if the for loop is not looping then, right?
So my question is, how to reduce a string or char array and print the decrement value over and over again?
Here is my code so far for it.
public String wordDown(String userString, int userNum)
{
String stringModded = userString.substring(0, userNum);
char[] charArray = stringModded.toCharArray();
char repeat = ' ';
for(int i = 0; i<userNum; ++i)
{
repeat = (char) (repeat +charArray[i]);
charArray[i] = repeat;
for(int j = 1; i > charArray.length; ++j)
{
String modWord = String.valueOf(charArray[i + 1]);
return modWord;
}
}
return null;
}
public static void main(String[] args)
{
int userNumber;
String userString;
RandomArrayFunctionalities ranMethod = new RandomArrayFunctionalities();
Scanner in = new Scanner(System.in);
System.out.println("\nEnter a word:");
userString = in.next();
System.out.println("\nEnter a number within the word scope that you just enter:");
userNumber = in.nextInt();
System.out.println(ranMethod.wordDown(userString, userNumber));
}
You do not need to modify the original array. Use a StringBuilder to concatenate the successive parts of the word. Use the String.substring(int,int) method to pull out those parts. The example that follows uses a decrementing index to generate the successively smaller substrings.
public String wordDown(String word, int userNum) {
StringBuilder sb = new StringBuilder();
for (int length = userNum ; length > 0 ; --length) {
sb.append(word.substring(0, length));
}
return sb.toString();
}
I think you are over complicating things, you don't need a char array at all and you only need a single loop, and a single return statement:
public String wordDown(String userString, int userNum) {
String finalString = "";
for (int i = 0; i < userNum; ++i) {
finalString = finalString + userString.substring(0, userNum - i);
}
return finalString;
}
Simply loop up to the inputted number and substring from 0 to inputtedNumber - loopCounter and append the result to the previously held String value.
Example Run:
Enter a word:
Calculus
Enter a number within the word scope that you just enter:
5
CalcuCalcCalCaC
Sidenote:
Technically you would want to use StringBuilder instead of appending String in a loop, but that is probably out of the scope of this question. Here is that version just for reference:
public String wordDown(String userString, int userNum) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < userNum; ++i) {
sb.append(userString.substring(0, userNum - i));
}
return sb.toString();
}

How to reverse the word after getting a Capital letter at the end of the word in JAVA?

Suppose you have a String and a CAPITAL letter in that indicates ending of a word. For example, if you have wElovEcakE where E, E and K indicates end of the words wE, lovE and cakE respectively. You need to reverse each word (as you know where it ends). Don’t reverse the String as a whole. To illustrate, if we give wElovEcakE as input output should be EwEvolEkac. See wE became Ew, lovE became Evol and so on....
And the way i tried to approach with ..
import java.util.Scanner;
public class Alternative {
public static void main(String[]args) {
Scanner robo=new Scanner (System.in);
System.out.println("Enter a word ");
String word=robo.nextLine();
char[] array=word.toCharArray();
for(int i =0;i<array.length;i++){
int count =0;
for(int j=0;j<=("EMPTY");j++) // here i am trying to operate a loop where it will work up to the Capital letter.
count ++;
}
//Code incomplete
}
}
}
Above i have mentioned "EMPTY" in the condition part ... i want to operate a loop where my loop will work up to the capital letter , then i will count all the letter that i have counted up to capital letter then last step will be like i will make another loop where i will reverse all the letter where condition for the loop will <=count ;Example:lovE (counted 4 letters i will reverse four times back).
Can you guys help me to write the condition at "EMPTY" part if you think that my approach is correct ..
Can you guys help me to solve the problem in any other way ?
test if this works for you:
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
String textInvert = "";
int indexAnt = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
String wordSplit = word.substring(indexAnt, i + 1);
for (int j = wordSplit.length() - 1; j >= 0; j--)
textInvert += wordSplit.charAt(j);
indexAnt = i + 1;
}
}
System.out.println(textInvert);
Here is my solution with Regex pattern
String[] in = "wElovEcakE".replaceAll("([A-z]+?[A-Z])","$1,").replaceAll(",$","").split(",");
String out = "";
for(String current: in){
StringBuilder temp = new StringBuilder();
temp.append(current);
out+=temp.reverse();
}
System.out.println(out);
Result:
EwEvolEkac
Here is a solution that makes use of the StringBuilder class to hold and reverse each found word.
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word:");
String word = robo.nextLine();
robo.close();
String upperCase = word.toUpperCase(); //used to find uppercase letters
StringBuilder builder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char nextChar = word.charAt(i);
builder.append(nextChar);
if (nextChar == upperCase.charAt(i)) {
String subWord = builder.reverse().toString();
System.out.print(subWord); //It's not clear what to do with the found words
builder = new StringBuilder();
}
}
System.out.println();
Example
Enter a word:
makEmorEpiE
EkamEromEip
You can try this solution:
String textInvert = "wElovEcakE";
String revertText = textInvert
.chars().mapToObj(c -> (char) c)
.reduce(new LinkedList<>(Arrays.asList(new StringBuilder())), (a, v) -> {
a.getLast().append(v);
if (Character.isUpperCase(v)) {
a.add(new StringBuilder());
}
return a;
}, (a1, a2) -> a1)
.stream()
.map(s -> s.reverse())
.reduce(StringBuilder::append)
.map(StringBuilder::toString)
.get();
System.out.println(revertText);
public class Alternative {
public static void main(String[] args) {
Scanner robo = new Scanner(System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
char[] array = word.toCharArray();
int count = -1;
for (int i = 0; i < array.length; i++) {
if (Character.isUpperCase(array[i])) { //find the upper case letters in the word
for (int j = i; j > count; j--) //loop through the letters until the last count variable value is encountered
System.out.print(array[j]); //print the reversed values
count = i; //assign the last encountered uppercase letter's index value to count variable
}
}
}
}

with help of only charAt() and isSpaceChar() make first latter uppercase in java

I want to use only charAt() and toUpperCase() function and capitalize the first letter of each word in a sentence.
Like make the letter capital, that is just after the space.
I tried with this following code.
import java.util.Scanner;
class firstscap
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a sentence");
String s=sc.nextLine();
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
if(Character.isSpaceChar(c))
{
char ch=s.charAt(++i);
ch=ch.toUpperCase();
}
}
System.out.println(s);
}
}
Several problems here.
s.charAt(n) gives you the n-th character of the String, not a pointer to the n-th character of the String. Changing that character does nothing to the String.
Also Strings are not mutable, which means you have no way to change them.
You can start build a new String from parts of the old String plus the Chars you have made uppercase.
You are capitalizing the characters but not storing them anywhere. I recommend you append all the characters to a StringBuilder*.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = sc.nextLine().trim(); // Input & omit leading/trailing whitespaces
StringBuilder sb = new StringBuilder();
// Append the first character, capitalized
if (s.length() >= 1) {
sb.append(Character.toUpperCase(s.charAt(0)));
}
// Start with character at index 1
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isSpaceChar(c)) {
sb.append(c).append(Character.toUpperCase(s.charAt(++i)));
} else {
sb.append(c);
}
}
s = sb.toString();
System.out.println(s);
}
}
A sample run:
Enter a sentence: hello world how are you?
Hello World How Are You?
* You can use String instead of StringBuilder but I recommend you use StringBuilder instead of String for such a case because repeated string concatenation in a loop creates additional as many instances of String as the number of concatenation. Check this discussion to learn more about it.
Strings are immutable, you can't modify them.
Consider building a new String for the result e.g by using StringBuilder.
In the following example, a boolean flag is used to know if the last character was a space .
Also we check if the current character is a letter before putting it to upper case, otherwise it makes no sense.
This will also prevent possible crashes if the line ends with a space (since index charAt(i+1) would crash):
public static void main(final String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("enter a sentence");
String s = sc.nextLine();
boolean wasSpace = false;
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
if (wasSpace && Character.isLetter(c)) {
resultBuilder.append(Character.toUpperCase(c));
} else {
resultBuilder.append(c);
}
wasSpace = Character.isSpaceChar(c);
}
System.out.println(resultBuilder.toString());
}
Note :
If you also want the first letter of the whole sentence to be capitalized, just initialize wasSpace to true .
import java.util.Scanner;
public class A {
public static void main(String args[]) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter the string: ");
String a1 = (obj.nextLine()).trim();
String s1 = "";
char c2;
char arr[] = a1.toCharArray();
for (int i = 0; i <= a1.length() - 1; i++) {
if (Character.isSpaceChar(arr[i]) == true) {
++i;
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + " " + c2;
} else {
if (i == 0) {
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + "" + c2;
} else {
s1 = s1 + arr[i];
}
}
}
System.out.println(s1);
}
}

swapping two letters in an unknown string in java

i am writing a program that must scramble a word. First I read in the word backwards using .reverse. Then I turned the string into a charArray.I am suppose to create a for loop to figure out if the First letter is "A" and if it is then i have to see if the next letter is not an "A". if its not then i am suppose to swap the two letters. If any of the two letters have a;ready been swapped than they cannot be swapped again.
Some examples are
Input: “TAN” Output: “ATN”
Input: “ALACTRIC” Output:“AALCTRIC”
Input: "Fork" Output:"Fork"
Here is my code so far: i cannot figure out what to put in the for loop. Thank you!
import java.util.Scanner;
public class scrambleWordRetry {
public static void main(String[] args)
{
}
public static String scramble( Random random, String inputString)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word to scramble.");
inputString = scan.nextLine();
char a[] = inputString.toCharArray();
for( int i=0 ; i<a.length-1 ; i++ )
{
}
return inputString;
}
}
I hope this code is useful for you
Scanner x = new Scanner(System.in);
String str = x.next();
System.out.println("Before Swapping" + str);
str = scramble(str);
System.out.println("After Swapping " + str);
}
public static String scramble(String inputString) {
char s[] = inputString.toCharArray();
for (int i = 1; i < s.length; i++) {
if (s[i] == 'A' || s[i] == 'a') {
char temp = s[i - 1];
s[i - 1] = s[i];
s[i] = temp;
}
}
return new String(s);
}
then if you input 'ALACTRIC' the output will be 'AALCTRIC',
'Tan = aTn',
'fork = fork'.

By using while/for loop, how to subtract ONLY the uppercase of a line input by users?

Here is my code, i used is.upperCase to check but it doesn't seem to work. And i have trouble concatenating all the uppercases together. Any suggestion and help would be appreciated!
import java.util.Scanner;
public class UpperCase {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.next();
int i = 0;
while (i < str.length() - 1) {
if(Character.isUpperCase(i)) {
char upperLetter = str.charAt(i);
}
Object outputLetter = str.charAt(0) + str.charAt(i++);
char upperLetter = str.charAt(i++);
}
System.out.println("The uppercase letters are:" );
}
}
I guess below would solve your problem.
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.nextLine();
char[] cr = str.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
for(int i=0;i<cr.length;i++){
if(Character.isUpperCase(cr[i])){
stringBuffer.append(cr[i]);
}
}
System.out.println("The uppercase letters are:" + stringBuffer);
First, your idea is correct, but the way you did implement has some mistakes
1. isUperCase of i -> Wrong
2. outputLetter should be declare outside the loop to advoid re-init data
3. outputLetter should be something like outputLetter += anUpperCase
4. finally, refer this bellow code
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.next();
in.close();
int i = 0;
String result = "";
while (i < str.length() - 1) {
char aChar = str.charAt(i);
if (Character.isUpperCase(aChar)) {
result += aChar;
}
i++;
}
System.out.println("The uppercase letters are: " + result);
}

Categories