Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to reverse a String, I know there are thousands of examples, but I wanted to do the job by myself and I created this, but it doesn't work properly.
public String ReverseString(String str){
str = str.toLowerCase();
char normalArr[] = str.toCharArray();
char reversedArr[] = new char[str.length()];
for (int i=str.length()-1; i<=0; i--){
int count = 0;
reversedArr[count] = normalArr[i];
count++;
}
String retValue = new String(reversedArr);
return retValue;
}
In addition to #zaskes answer, you want int count = 0; before the loop, not inside.
Look at the condition of your loop - it should be i >= 0
In addition - your solution allocates an unnecessary array (there are algorithms that perform this with a single array, not yours , though) - I think you should strive to code your programs to be with good performance.
Here's an implementation that does the reverse logic:
StringBuffer reversed = new StringBuffer(str.length());
int loc = str.length();
while (loc > 0) {
char c1 = str.charAt(--loc);
if (Character.isLowSurrogate(c1)) {
assert loc >= 0;
char c2 = str.charAt(--loc);
reversed.append(c2);
}
reversed.append(c1);
}
return reversed.toString();
If you consider the use of StringBuffer for simple appends cheating, you can replace that with:
char[] reversed = new char[str.length()];
int next = 0;
...
reversed[next++] = c1; // instead of .append(c1)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I would like to swap every second character of a string like so:
welcome -> ewclmoe
How can I do this?
I would prefer to build the output with a StringBuilder. Iterate the even indices of the original String. First append the next odd character (if there is one), then take the even character. Like,
String s = "welcome";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i += 2) {
if (i + 1 < s.length()) {
sb.append(s.charAt(i + 1));
}
sb.append(s.charAt(i));
}
System.out.println(sb);
Outputs (as requested)
ewclmoe
below code works...
check it out...
public static void swapCharacter(String s) {
char[] a = s.toCharArray();
char temp;
for(int i=0; i<a.length-1;i+=2)
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
System.out.println(new String(a));
}
public static void main(String[] args) {
swapCharacter("welcome");
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am new towards coding, so I've managed to create a code that allows me to reverse words, however, I don't fully understand the for loop construct, because I created this using online resources.
public class word {
public static String rWords(String input) {
String[] split = input.split("");
String output = " ";
for (int i = split.length - 1; i >= 0; i--) {
output += (split[i] + "");
}
return output.trim();
}
}
Say there is already a main class that contains a string value of input, this is another class called word, I understand that making it public static string means it's public and static means it's not declared in instances. It contains one parameter with the input from main class, the output is empty for my for loops results to go into that, however, how does the for loop allow my input to be reversed and return.trim do?
Why don't you use out-of-box approach? E.g. StringBuilder already has a method reverse():
public static String reverseWords(String str) {
return Arrays.stream(str.trim().split("\\s+"))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
}
But you string can do it with old Java:
public static String reverseWords(String str) {
// using StringBuilder for multiple string concatenation
StringBuilder buf = new StringBuilder(str.length());
for (String word : str.trim().split("\\s+")) {
// add space if word is not first one
if (buf.length() > 0)
buf.append(' ');
// add each word from end to beginning
for (int i = word.length() - 1; i >= 0; i--)
buf.append(word.charAt(i));
}
return buf.toString();
}
In case you need swap words in the sentence, principle is the same:
public static String reverseWords(String str) {
StringBuilder buf = new StringBuilder(str.length());
String[] words = str.trim().split("\\s+");
for (int i = words.length - 1; i >= 0; i--) {
if (buf.length() > 0)
buf.append(' ');
buf.append(words[i]);
}
return buf.toString();
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I currently have an assignment where we have the entire (swedish) alphabet in lower case as a string, and we should convert every other character to upper case. This is where I am right now:
public static void main(String[] args) {
String alphabet = "abcdefghijklmnopqrstuvwxyzåäö";
System.out.println(alphabet);
for (int i = 0; i < 29; i = i + 2) {
char result = alphabet.charAt(i);
alphabet.toUpperCase(result);
}
System.out.println(alphabet);
}
The problem now is that alphabet.toUpperCase(result); gives me an error that I can't convert char to locale. How do I fix this?
If you want to get the uppercase of a char, you should use Character.toUpperCase(c), not String's toUpperCase.
So, I think you might be looking for something like this:
public static void main(String[] args) {
String alphabet = "abcdefghijklmnopqrstuvwxyzåäö";
System.out.println(alphabet);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < alphabet.length(); i++) {
char c = alphabet.charAt(i);
sb.append(i % 2 == 0 ? Character.toUpperCase(c) : c);
}
String result = sb.toString();
System.out.println(result);
}
Output:
abcdefghijklmnopqrstuvwxyzåäö
AbCdEfGhIjKlMnOpQrStUvWxYzÅäÖ
Since Strings are immutable, you have to create a new String to get what you want. An efficient way of doing this is with a StringBuilder.
Edit:
Another way to do it without StringBuilder and perhaps a more intuitive way is to convert the String to an array of chars, which makes it mutable. In the end, you just convert it back to a String. The result would look like this:
public static void main(String[] args) {
String alphabet = "abcdefghijklmnopqrstuvwxyzåäö";
System.out.println(alphabet);
char[] chars = alphabet.toCharArray();
for (int i = 0; i < alphabet.length(); i+=2) {
chars[i] = Character.toUpperCase(chars[i]);
}
String result = new String(chars);
System.out.println(result);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm pretty new to Java, and I need to solve this problem for an assignment. Can anyone help me please?
The problem is we need to enter a String like "AUGUUUUCU" and then split it into three letter strings like "AUG", "UUU", "UCU".
After that I would have to iterate over these and translate them to "AUG = METIONINA", "UUU = FENILANINA", "UCU = SERINA". Can anyone help me with this?
I already found a way to split them:
public class Main {
public static void main(String[] args) {
String str = "AUG-UUU-UCU";
String delimiter = "-";
String[] temp;
temp = str.split(delimiter);
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
}
}
If you're supposed to take user input, then you'll need to use a Scanner:
Scanner sc = new Scanner(System.in);
String input = sc.next();
To split it into three-letter Strings, use an array and store the substrings in the array using a for loop:
String[] subs = new String[input.length()/3];
int index;
for (int i=0; i<input.length(); i++) {
index = i*3;
subs[i] = input.substring(index, index+3);
}
You could then iterate over the array with another for loop and use a switch statement to determine the correct output:
for (int i=0; i<subs.length; i++) {
switch(subs[i]) {
case "AUG":
System.out.println("METIONINA");
break;
case "UUU":
System.out.println("FENILANINA");
break;
case "UCU":
System.out.println("SERINA");
break;
default:
break;
}
}
Note the break statements within the switch block. These are important to include; without break statements, it will simply execute all code after the matching case.
You could create an array that holds the values that are to be translated.
translateArray = new String[3];
Then you could set the values of the parallel array based on the input you receive. Then you could post those values.
for (int i=0; i<temp.length ; i++) {
if (temp[i] == "AUG" ) {
translateArray[i] = "METIONINA";
}
if (temp[i] == "UUU") {
translateArray[i] = "FENILANINA";
}
if (temp[i] == "UCU") {
translateArray[i] = "SERINA";
}
System.out.println(temp[i] + " = " + translateArray[i]);
}
Maybe that will work better for you.
To split a string into strings 3 chars long is 1 line:
String[] words = str.split("(?<=\\G...)");
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have seen this and this question but mine is different. I want to write an efficient code for it in java. I came up with 2 solutions:
Approach 1.
find_first_reapeted(char[] input)
{
HashMap<Character,Integer> myhash = new HashMap<Character,Integer> ();
for(int i=0;i<input.length;i++)
{
if(myhash.containsKey(input[i])
myhash.put(input[i],2); //just put 2 even if it is more than 2
else
myhash.put(input[i],1);
}
for(int i=0;i<input.length;i++)
{
if(myhash.getValue(input[i])==1)
return input[i];
}
}
Approach 2.
find_first_reapeted(char[] input)
{
int[] allchars = new int[26];
for(int i=0;i<input.length;i++)
{
allchars[input[i]-'a'] += 1;
}
for(int i=0;i<input.length;i++)
{
if(allchars[input[i]-'a']==1)
return input[i];
}
}
First is there any better solution? (int term of time and space complexity)?
If not which one of the the above is better? I'm not sure about the space complexity of hashmap!
How about
The first repeating character.
char find_first_repeated(char[] input) {
BitSet bs = new BitSet();
for(char c : input) {
if(bs.get(c))
return c;
bs.set(c);
}
return '\uffff'; // invalid char
}
The first non repeating character, I would use the second approach but using the for-each loop to make it cleaner.