Replace "*" with "-" in given character array - java

Given character array is
char[] arr = {123*4*5}
output should be
String str = "123-4-5"

1) That's not how you declare a char array. As pointed in comments it should be:
char[] arr = {'1','2','3','*','4','*','5'};
2) If you want a String why don't you start with a String?
3) You could construct a String from a char[] and use String.replace(char oldchar, char new char) which comes as the first result in a Google search. Code:
char[] arr = {'1','2','3','*','4','*','5'};
String str = String.valueOf(arr).replace('*', '-');
4) If you need to do it on a char[] before a String is made, you could simply loop through the array:
char[] arr = {'1','2','3','*','4','*','5'};
for(int i=0; i<arr.length; i++)
if(arr[i] =='*') arr[i] = '-';
String str = String.valueOf(arr);
EDIT: based on the comments and discussion with OP, the question seems to be exactly as posted. That is:
char[] arr = {xxx*y*z};
String str = transformCharArr(arr);
For arr={123*4*5}: str = "123-4-5" and for arr={122*2}: str = "122-2".
Therefore, I made a small function that achieves just that and solves both cases.
Assumptions:
1) xxx is always a three digit number, minimum is 100, maximum is 999.
2) y is non-zero 1 digit number [1-9], same with z.
3) In case y or z is equal to 1, it's ignored given multiplication by 1 changes nothing to the outcome.
4) xxx is always minimized. That is, for 123*4*5, the lowest possible xxx to achieve this is 123 with respect to assumption (1) that xxx>=100.
5) y and z are maximized with z being favored for maximization. Also with respect to assumption (2) for both.
Therefore, code is:
static String transformCharArr(char[] arr){
if(arr.length > 1) return ""; // array should only contain 1 element
int value = (int)arr[0]; // using int since char is the only unisgned 2-byte type in all of Java, short isn't enough given MAX(short) = 32,767 while max(char) = 65,535
short xxx=100, y=1, z=1; // all shorts since they never exceed certain limits
int product = 0; // to stop the loop, int because short*short*short gives int type, and product is comparable to value, so it has to support more than max(short)
for(xxx=100; xxx<=999; xxx++){ // first loop xxx to minimize it
for(y=1; y<=9; y++){ // loop y before z to favor maximizing z
for(z=1; z<=9; z++){ // ensures maximizing z before y
if((product = xxx*y*z)== value)
break;
}
if(product == value) break;
}
if(product == value) break;
}
if(y==1) return String.format("%d-%d", xxx, z); // if y is 1, ignore it
if(z==1) return String.format("%d-%d", xxx, y); // if z is 1 ignore it
return String.format("%d-%d-%d", xxx,y,z);
}
Testing it:
public static void main(String[] args) {
char[] arr1 = {123*4*5};
System.out.println(transformCharArr(arr1));
char[] arr2 = {122*2};
System.out.println(transformCharArr(arr2));
}
Output:
123-4-5
122-2
Analysis:
Time-complexity: O(C) given the loop cannot run more than 999*9*9 and it is ALWAYS guaranteed to find value before xxx=9 y=9 z=9 given that 999*9*9 = ‭80,919‬ > max(char)=65,535

The first thing you should know is that the 123 * 4 * 5 means 2460,so the point by upstairs is right.which like this :
char[] arr = {'1','2','3','*','4','*','5'};
System.out.println(new String(arr).replaceAll("\\*","-"));

char[] arr = {'1','2','3','*','4','*','5'};
String str = String.valueOf(arr).replace('*', '-');
get a string from your char arrays and take the replace method to repalce '*' from '-'

Related

Problem replacing char in char array with a digit

Given a string, I have to replace all vowels with their respective position in the array. However, my code returns some strange symbols instead of numbers. Where's the problem?
String s = "this is my string";
char p = 1;
char[] formatted = s.toCharArray();
for(int i = 0; i < formatted.length; i++) {
if(formatted[i] == 'a' ||formatted[i] == 'e' ||formatted[i] == 'i'
||formatted[i] == 'o' ||formatted[i] == 'u') {
formatted[i] = p;
}
p++;
}
s = String.valueOf(formatted);
System.out.println(s);
P.S: Numbers are bigger than 10
this is my s t r i n g
012345678910 11 12 13 14
The position of i in string is 14 but 14 is not a character; it's a numeric string. It means that you need to deal with strings instead of characters. Split s using "" as the delimiter, process the resulting array and finally join the array back into a string using "" as the delimiter.
class Main {
public static void main(String[] args) {
String s = "this is my string";
String[] formatted = s.split("");
for (int i = 0; i < formatted.length; i++) {
if (formatted[i].matches("(?i)[aeiou]")) {
formatted[i] = String.valueOf(i);
}
}
s = String.join("", formatted);
System.out.println(s);
}
}
Output:
th2s 5s my str14ng
The regex, (?i)[aeiou] specifies case-insensitive match for one of the vowels where (?i) specifies the case-insensitiveness. Test it here.
The character '1' has a different value from the number 1.
You can change
char p = 1;
to
char p = '1';
and I think that will give you what you want, as long you're not trying to insert more than 9 numbers in your string. Otherwise you'll need to cope with inserting extra digits, which you cannot do into a char-array, because it has a fixed length.
the root of the problem is already in the comments,
in java the types make a difference in memory size and its representation
int x = 1;
and
char y = '1'
are not holding the same value, this is because many numerical representations are related with ascii codes and the value you have to assing to y to get the number 1 printed is HEX 0x31 or DEC 49.
take a look at the ascci table

Not able to understand the code to Count Duplicates in a string?

This program finds the count of duplicates in a string.
Example 1:
Input:
"abbdde"
Output:
2
Explanation:
"b" and "d" are the two duplicates.
Example 2:
Input:
"eefggghii22"
Output:
3
Explanation:
duplicates are "e", "g", and "2".
Help me with this code.
public class CountingDuplicates {
public static int duplicateCount(String str1) {
// Write your code here
int c = 0;
str1 = str1.toLowerCase();
final int MAX_CHARS = 256;
int ctr[] = new int[MAX_CHARS];
countCharacters(str1, ctr);
for (int i = 0; i < MAX_CHARS; i++) {
if(ctr[i] > 1) {
// System.out.printf("%c appears %d times\n", i, ctr[i]);
c = ctr[i];
}
}
return c;
}
static void countCharacters(String str1, int[] ctr)
{
for (int i = 0; i < str1.length(); i++)
ctr[str1.charAt(i)]++;
}
}
You need to maintain a count and if the value of that character exceeds 1, you need to increment the count.
Return that count to know the count of duplicates.
Added comments to understand the code better.
public class CountingDuplicates {
public static int duplicateCount(String str1) {
// Initialised integer to count the duplicates
int count = 0;
// Converting a string to lowercase to count lowerCase and Uppercase as duplicates
str1 = str1.toLowerCase();
// According to ASCII, the Maximum number of characters is 256,
// So, initialized an array of size 256 to maintain the count of those characters.
final int MAX_CHARS = 256;
int ctr[] = new int[MAX_CHARS];
countCharacters(str1, ctr);
for (int i = 0; i < MAX_CHARS; i++) {
if(ctr[i] > 1) {
// System.out.printf("%c appears %d times\n", i, ctr[i]);
count = count + 1;
}
}
return count;
}
static void countCharacters(String str1, int[] ctr)
{
for (int i = 0; i < str1.length(); i++)
ctr[str1.charAt(i)]++;
}
}
In short it is counting the number of characters appearing in the String str and saving it in ctr array.
How? ctr is the array that has a length of 256. So it can have 256 values (0-255 indexed). str1 is the string that contains the String. charAt(i) method returns the character at index i. Because String acts like an array where you can access each char a index values of an array.
Now assuming your input will always ASCII characters, each ASCII chars contain a value of 0-255 (i.e. ASCII value 'a' is 97). ++ after any variable means adding 1 to that. i.e.c++ means c = c+1
Now coming to the loop, ctr[str1.charAt(i)]++;, you can see the loops starts from 0 and ends at the length of the String str where 0 is the first value str. So if value of 0 indexed value (first value) of the String str is a, str.charAt(0) would return 97(well actually it will return 'a' but java takes the ASCII value). so the line actually is (for 0 th index) ctr[97]++; so it's incrementing the value of the 97th index (which is initially 0) by 1. So now the value is 1.
Like this way it will only increment the index values that matches with the ASCII values of the character in the String, thus counting the amount of time the characters occur.

How can I reprint a string starting from the first character till the last?

Given a non-empty string str like "Code" print a string like "CCoCodCode". Where at each index in the string you have to reprint the string up to that index.
I know there is DEFINITELY something wrong with this code that I wrote because the answer should be CCoCodCode, but instead it's giving me the alphabet! I don't know how I should change it.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String str = scan.next();
int x = str.length();
for(char i = str.charAt(0); i <= str.charAt(x-1); i++)
{
System.out.print(i);
}
}
The char datatype can be treated as a number; you can increment it and manipulate it as a number.
What you really want is successive substrings of str to be printed. Loop over an int that will represent the ending position of the substring to be printed.
for (int i = 0; i < str.length(); i++)
{
System.out.print(str.substring(0, i + 1));
}
The end index argument to substring is exclusive, which is why I added 1.
Let's say that str is "Code". We can perform some mental substitutions to see what happens to your loop.
str is "Code"
x is 4
str.charAt(0) is 'C'
str.charAt(x-1) is 'e'
Making these substitutions, your loop is:
for(char i = 'C'; i <= 'e'; i++)
{
System.out.print(i);
}
Does this help you see the problem? I would think you'd have a loop from 0 to 3, not from 'C' to 'e'...
Many ways to get it done, suppose we have the input from user stored in a string named "c"... then...
String c = "Code";
for (int i = 0; i < c.length(); i++) {
System.out.print(c.substring(0, i));
}
System.out.print(c);
And this will print the sequence you are looking for.
It is outputting the alphabet because you are printing the counter instead of the characters in the string!
As it is, the first iteration of the for loop will set i to the first character, print that, then the operation i++ will increment i by one. Wait, so if the first character is "C", so i = 'C', what is i++?
Well it turns out characters can be represented by numbers. For example, 'C' has a value of 67. So incrementing it makes it 68, which represents 'D'. So if you run the loop on "Code", it will increment your counter 4 times, giving "CDEF". If you run on "Codecodecode", that will make the loop run 12 times, giving "CDEFGHIJKLMN".
What you really want is to loop through the string by its index instead:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.next();
int length = str.length();
for (int i = 0; i < length; i++) {
System.out.print(str.substring(0, i + 1));
}
}

java split unknown length of string in every 3 parts

public static void main(String[] args) {
String brandmodel="VolkswagenGolf";
String [] splitedstring=new String[13]
//how to insert every 3 letters in splitedstring array
}
What i want is to split the above string in every 3 letters.
For example
i want to save from the above string the next
Vol,ksw,age,nGo,lf
i have read here some crazy codes but i did not understand them,i want the simplest way.
I have not learned Regex yet
Calculate the number of parts you will have and create an array:
int parts = (string.length() + 2) / 3;
String splitted[] = new String[parts];
Fill the array, using String.substring(int, int):
for (int i = 0; i < parts; ++i)
{
int x = i * 3;
splitted[i] = string.substring(x, Math.min(string.length(), x + 3));
}
Substring takes a string out of another string, using indices.
The problem is that if you take a range that goes out of the string, an exception will be thrown. So what I do, is limiting the endIndex to the string length, by using Math.min(int, int). It will always return the smallest of the two passed values.
Example of this going wrong, without Math.min():
String str = "test";
String substr = str.substring(2, 9);
This fails (Exception) because, 9 is out of the range of str. str is only 4 characters long. So, valid startIndices are: {0, 1, 2, 3} and valid endIndices are in this case: {0, 1, 2, 3, 4}.
You could use regex look-behind matching the last match plus any 3 characters:
String[] splitString = brandmodel.split("(?<=\\G...)");
The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))
Output:
[Vol, ksw, age, nGo, lf]
There's no "crazy code" required, it's a relatively straightforward:
String[] res = new String[(s.length()+2)/3];
for (int i = 0 ; i != res.length ; i++) {
res[i] = s.substring(3*i, Math.min(3*i+3, s.length()));
}
On ideone: link.
It works for all length of String
String brandmodel="VolkswagenGolf";
List <String> splitedstring = new ArrayList<String>();
int i = 0;
while(brandmodel.length() > 2 )
{
splitedstring.add(brandmodel.substring(0,3));
brandmodel = brandmodel.substring(3);
}
if(brandmodel.length() > 0)
splitedstring.add(brandmodel);

I want to be able to convert numbers into text according to the ASCII decimal table

I am trying to make it so that I can take individual three-character substrings and convert them to integers under the conditions tht the length of the String is a multiple of three. The integers into which the partioned substrings are converted are supposed to function as relative positions in an array that contains all the printing characters of the ASCII table.
String IntMessage = result.toString();
if
{
(IntMessage.substring(0,1)=="1" && IntMessage.length()%3==0)
for(j=0;j < IntMessage.length()-2;j += 3)
n = Integer.parseInt(IntMessage.substring(j,j+3));
mess += ASCII[n-32];
return mess;
Under otherwise conditions, the method should take the first two characters of the String and initialize them to a variable i. In this case, the variable mess is initialized to the character in the ASCII array with an index of i-32. Then there is a for loop that takes the remaining characters and partitions them into three-digit substrings and they are taken and changed into strings according to their corresponding positions in the ASCII array. The String variables in this array are continuously added on to the the variable mess in order to get the BigInteger to String conversion of the IntMessage String.
int i = Integer.parseInt(IntMessage.substring(0,2));
mess=ASCII[i-32];
for(l=2; l< IntMessage.length() - 2; l+=3)
r = Integer.parseInt(IntMessage.substring(l,l+3));
mess+=ASCII[r-32];
return mess;
For some reason the method isn't working and I was wondering whether I was doing something wrong. I know how to take an input String and convert it into a series of numbers but I want to do the opposite also. Is there anyway you could help?
Based on your description you can use the following methods:
String fromIntMessage(String msg) {
StringBuilder result = new StringBuilder();
for (int x = (msg.length() % 3 - 3) % 3; x < msg.length(); x += 3) {
int chr = Integer.parseInt(msg.substring(Math.max(x, 0), x + 3));
result.append(Character.toString((char) (chr - 32)));
}
return result.toString();
}
String toIntMessage(String string) {
StringBuilder result = new StringBuilder();
for (char c : string.toCharArray()) {
result.append(String.format("%03d", c + 32));
}
return result.charAt(0) == '0' ? result.substring(1) : result.toString();
}
which will give you
toIntMessage("DAA") // => "100097097"
fromIntMessage("100097097") // => "DAA"

Categories