Convert characters to upper without changing original array - java

I have the following code which changes lowercase letters to uppercase letters of the private instance array letters and returns a string.
public String toUpperCase()
{
char[] duplicate = new char [letters.length];
duplicate = letters;
String upperCase = "";
int a = 0;
int b = 0;
for (int i =0; i < duplicate.length; i++)
{
a = duplicate[i];
if (a >= 97 && a <= 122)
{
b = a - 32;
duplicate[i] = (char) b;
}
upperCase = upperCase + duplicate[i];
}
return upperCase;
}
the problem is the original contents of the array letters have been changed to uppercase after this method is called. I created a new array, duplicate, and set it equal to letters in hopes I can change the lowercase letters in the array letters to uppercase without changing the original array. However, this didn't work. How can I change the lowercase letters of the array letters to uppercase without changing the original array?

try this:
char[] duplicate = letters.clone();
that way the original array does not change

How can I change the lowercase letters of the array letters to uppercase without changing the original array?
Don't assign the letter array instance to the variable duplicate. Instead use System.arraycopy(letters, 0, duplicate, 0, letters.length) which copies the contents of letters to duplicate.

duplicate = letters; ... you are assigning the original value to the duplicates, these two arrays now point to the same location. So any modifications to duplicate will be mirrored by letters automatically (they both point to the same location in memory).
Instead, you need to use letters to obtain the original values and store the modifications within duplicate
public String toUpperCase() {
char[] duplicate = new char[letters.length];
String upperCase = "";
int a = 0;
int b = 0;
for (int i = 0; i < letters.length; i++) {
a = letters[i];
if (a >= 97 && a <= 122) {
b = a - 32;
duplicate[i] = (char) b;
}
upperCase = upperCase + duplicate[i];
}
return upperCase;
}
Unless you have some reason not to, you can also make use of the Character class to help you detect lower case characters and convert them to upper case, for example...
if (Character.isLowerCase(a)) {
letters[i] = Character.toUpperCase(a);
}
or you could just use letters[i] = Character.toUpperCase(a); as it won't double convert upper case characters
This all leads me to wonder why you need the duplicate array to begin with, in the end, you could just get away with something like...
public String toUpperCase() {
StringBuilder upperCase = new StringBuilder(letters.length);
for (char c : letters) {
upperCase.append(Character.toUpperCase(c));
}
return upperCase.toString();
}
or just
public String toUpperCase() {
return new String(letters).toUpperCase()
}

While other answers work too, you don't actually have to copy the array...
Just do,
if (a >= 97 && a <= 122)
{
b = a - 32;
upperCase = upperCase + (char) b;
}
else
upperCase = upperCase + duplicate[i];

This doesn't do what you think it does:
char[] duplicate = new char [letters.length];
duplicate = letters;
The first line allocates a new array. The second line does not fill the new array. Far from it. The second line points duplicate to letters. That is, duplicate and letters both point to the same data. Manipulating duplicate manipulates letters too.
To make duplicate a real duplicate, you need to copy the content. An easy way to do just that:
char[] duplicate = letters.clone();
Another way to copy the content:
char[] duplicate = new char [letters.length];
System.arraycopy(letters, 0, duplicate, 0, letters.length);

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

How to remove unused elements from an array without the use of the Collections

I had an array of elements that I have converted in a String.
But this String keeps again the empty elements of the array and I can't compare it with another String.
How can I delete the empty elements on it?
I don't know how to use the Collections, is there another way?
char[] copyLoop = new char[26];
for (int i = 0; i < letters.length; i++) {
if (letters[i] > 1) {
char c = (char) (i + 97);
copyLoop[i] = c;
}
}
String rslt = String.copyValueOf(copyLoop);
return rslt;
There are no "empty" elements in an array, and you can't resize arrays either. All you can do is to put all of the elements you're interested in at one end of the array (e.g. starting at zero) with no "uninteresting" elements between them, and then construct a string from a portion of the array.
Use another variable to store the index of the next "empty" element in the array: every time you find a letter, increment this variable. Once you've finished iterating letters, this variable will contain the length of the array to use to create the string.
char[] copyLoop = new char[26];
int dst = 0;
for (int i = 0; i < letters.length; i++) {
if (letters[i] > 1) {
char c = (char) (i + 97);
copyLoop[dst++] = c;
}
}
return new String(copyLoop, 0, dst);
Or, of course, use a StringBuilder (which is doing effectively the same internally):
StringBuilder copyLoop = new StringBuilder(26);
for (int i = 0; i < letters.length; i++) {
if (letters[i] > 1) {
char c = (char) (i + 97);
copyLoop.append(c);
}
}
return copyLoop.toString();
Unfortunately not. Arrays in Java are not shrinkable/expandable, their size is set constant. There are two ways you can work around:
Use Collections, i.e. create a List of Characters ArrayList<Character> list = new ArrayList<>();, use it and delete items you don't need after each loop cycle.
On every cycle of your for loop, when you need to delete an item inside your Array, just create a new char[] array, which is smaller and copy the contents of the old one to the new, except for the value you deleted.
Also, if you are working with Strings, it's recommended to use mutable String classes s.a. StringBuilder or StringBuffer which let you add/remove characters from the String. In your case that seems to be the best solution.

Compare two strings in Java and show the character differences

I'm looking for a way to compare two strings to each other character by character.
It should show whether there are other characters which don't appear in both strings.
Does someone have a solution for?
for(int j=0; j < min; j++) {
s1 = w1.substring(j,j+1);
s2 = w2.substring(j,j+1);
if (!s1.equalsIgnoreCase(s2) ){
counter++;
}
}
This only looks sequential for differences. But I want to find out whether there are differences between those two strings at all.
So **abc** and **cab** should count as a hit
I think what you want is to show that 2 strings have the same letters and the same amount of each letter. Use 2 hashsets, where the key is the character and the value is the number of occurrence in the string. you'll have one hashset for each string, then loop through the string add the characters to the set and compare to see if the sets are equal.
Turn them into charArrays and add the differences to an empty string as a for loop scans through them, for instance
String a = "abc";
char[] aa = a.toCharArray();
String b = "cba";
char[] bb = b.toCharArray();
String dif;
public void differ() {
for(int i = 0; i < aa.length - 1; i++) {
if(!aa[i].equals(bb[i])) {
dif += aa[i];
}
}
}
I believe running differ() would return "ac" because they both have b in the middle. Is this what you wanted?

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