Problem replacing char in char array with a digit - java

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

Related

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

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 '-'

How do I count how many digits are in every string of an array?

The instructions are to count how many digits are in every string of an array and assign to numberDigits.
What am I doing wrong here?
public void computeStatistics(String []strings){
numberDigits = 0;
for(String s : strings){
for(int i : s.toCharArray()){
if(i >= 0 || i <= 2)
numberDigits++;
}
}
}
Alternatively, since overall digits count matter, all strings can be concatenated to single and each character can be checked for if it is digit.
public void computeStatistics(String[] strings) {
numberDigits = 0;
//Converting all strings in array to single string
String cmbStr = Arrays.toString(strings);
for (Character c : cmbStr.toCharArray()) {
//checking each character is digit
if (Character.isDigit(c))
numberDigits++;
}
}
Not really sure if i understood your question correctly are you counting the number of digits in a string array?
public int computeStatistics(String []strings){
int numberDigits = 0;
for(String s : strings){
s = s.replaceAll("\D+","");
numberDigits = numberDigits + s.length();
}
return numberDigits;
}
I am assuming that your string is alpha nummeric. Your if condition is wrong. char datatype have integer representations of their corresponding ASCII value. So char a = 'A' when casted to int is actually stored as 65. So the char '0' which is stored in the array you are iterating over is stored in i as 48. You are checking between 0 to 9 ascii codes and hence this code wont work. Either change if condition to
if(i>=48 && i<=57)
Or what i find as a good general policy is to keep char as char.
for(char ch:s.toCharArrat())
if(ch>='0' && ch<='9')
This way you wont have to think about ascii. For converting char '0' to int do the following.
int i = (int)ch - (int)'0';
This will give corresponding integers.

Compressing a file

I want to accomplish a program which can take a textfile and make the size smaller. So far it replaces all the double character occurrences, and now I want to replace "ou" with "1".
I've tried with an if-statement, but it doesn't seem to work quite well.
My method is below:
public String compressIt (String input)
{
int length = input.length(); // length of input
int ix = 0; // actual index in input
char c; // actual read character
int cCounter; // occurrence counter of actual character
String ou = "ou";
StringBuilder output = // the output
new StringBuilder(length);
// loop over every character in input
while(ix < length)
{
// read character at actual index then increments the index
c = input.charAt(ix++);
// we count one occurrence of this character here
cCounter = 1;
// while not reached end of line and next character
// is the same as previously read
while(ix < length && input.charAt(ix) == c)
{
// inc index means skip this character
ix++;
// and inc character occurence counter
cCounter++;
}
if (input.charAt(ix) == 'o' && input.charAt(++ix) == 'u' && ix < length - 1)
{
output.append("1");
}
// if more than one character occurence is counted
if(cCounter > 1)
{
// print the character count
output.append(cCounter);
}
// print the actual character
output.append(c);
}
// return the full compressed output
return output.toString();
}
It's this lines of code I'm referring to.
if (input.charAt(ix) == 'o' && input.charAt(ix + 1) == 'u')
{
output.append("1");
}
What I want to do: Replace characters. I got a text-file which contains "Alice In Wonderland". When my looping through all characters sees an 'o' and an 'u' (like "You"), I want to replace the characters so it looks like: "Y1".
Regards
So most likely you're trying loop from ix = 0 to the length of the string.
First of all my guess is that youre looping up and including string.length(). Which doesnt work, charAt is 0 indexed aka
"abc" has a charAt 0, 1 and 2 but not 3 which gives the error you describe.
Second of all the line you showed uses input.charAt (ix++) which does the following: get the char at position ix (old value) and after that, update the value ix to ix + 1, if you want ix to be updated before the surrounding charAt you'd have to write input.charAt(++ix)
Third of all there is a String.replace function, input.replace("abc", "def") will work great for simple replacements, for more complicated replacements, consider using regex.
This has nothing to do with the charAt method. You need to change your if condition to run it till length-1. It is failing in the last case as it is going out array.
for(int i=0; i<inputString.length() - 1; i++)
{
char temp = inputString.charAt(i);
char blah = inputString.charAt(i+1);
System.out.println("temp: "+ temp);
System.out.println("blah: "+ blah);
}
This works for me!

How to get numeric position of alphabets in java? [duplicate]

This question already has answers here:
How to map character to numeric position in java?
(7 answers)
Closed 5 years ago.
How to get numeric position of alphabets in java ?
Suppose through command prompt i have entered abc then as a output i need to get 123 how can i get the numeric position of alphabets in java?
Thanks in advance.
String str = "abcdef";
char[] ch = str.toCharArray();
for(char c : ch){
int temp = (int)c;
int temp_integer = 96; //for lower case
if(temp<=122 & temp>=97)
System.out.print(temp-temp_integer);
}
Output:
123456
#Shiki for Capital/UpperCase letters use the following code:
String str = "DEFGHI";
char[] ch = str.toCharArray();
for(char c : ch){
int temp = (int)c;
int temp_integer = 64; //for upper case
if(temp<=90 & temp>=65)
System.out.print(temp-temp_integer);
}
Output:
456789
Another way to do this problem besides using ASCII conversions is the following:
String input = "abc".toLowerCase();
final static String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i < input.length(); i++){
System.out.print(alphabet.indexOf(input.charAt(i))+1);
}
Convert each character to its ASCII code, subtract the ASCII code for "a" and add 1. I'm deliberately leaving the code as an exercise.
This sounds like homework. If so, please tag it as such.
Also, this won't deal with upper case letters, since you didn't state any requirement to handle them, but if you need to then just lowercase the string before you start.
Oh, and this will only deal with the latin "a" through "z" characters without any accents, etc.
char letter;
for(int i=0; i<text.length(); i++)
{
letter = text.charAt(i);
if(letter>='A' && letter<='Z')
System.out.println((int)letter - 'A'+1);
if(letter>='a' && letter<= 'z')
System.out.println((int)letter - 'a'+1);
}
This depends on the alphabet but for the english one, try this:
String input = "abc".toLowerCase(); //note the to lower case in order to treat a and A the same way
for( int i = 0; i < input.length(); ++i) {
int position = input.charAt(i) - 'a' + 1;
}
First you need to write a loop to iterate over the characters in the string. Take a look at the String class which has methods to give you its length and to find the charAt at each index.
For each character, you need to work out its numeric position. Take a look at this question to see how this could be done.
just logic I can suggest take two arrays.
one is Char array
and another is int array.
convert ur input string to char array,get the position of char from char and int array.
dont expect source code here
String word = "blah blah";
for(int i =0;i<word.length;++i)
{
if(Character.isLowerCase(word.charAt(i)){
System.out.print((int)word.charAt(i) - (int)'a'+1);
}
else{
System.out.print((int)word.charAt(i)-(int)'A' +1);
}
}

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