I would like to swap every second character of a string [closed] - java

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");
}

Related

Replace non-digit characters from an array of String and return a String Java [closed]

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 6 months ago.
Improve this question
I need to replace non-digit characters from an array of String and return a String with digits separated by coma, actually, I made it but don't like it.
The first thing I made, was added values from the String array to the String.
Then I replaced non-digit characters from a String.
After that, I added digit values to an int array and sorted it.
Then I added all this stuff to an array of strings and separated values with commas, after that I returned it.
I would be glad for advice, thanks for attention.
import java.util.Arrays;
class Test {
private static String sortedStringOfNumber(String[] string) {
StringBuilder temp = new StringBuilder();
for (String s: string) {
temp.append(s);
}
String numberOnly = temp.toString().replaceAll("[^0-9]", "");
int[] numbers = new int[numberOnly.length()];
for (int i = 0; i < numberOnly.length(); i++) {
numbers[i] = numberOnly.charAt(i) - '0';
}
Arrays.sort(numbers);
String[] result = new String[numbers.length];
for (int i = 0; i < numbers.length; i++) {
result[i] = String.valueOf(numbers[i]);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++) {
sb.append(result[i].toString());
if (i != result.length - 1)
sb.append(", ");
}
return sb.toString();
}
public static void main(String[] args) {
String[] arrayStringData = new String[] { "1", "ab3c", "level", null, "java2s.com", "asdf 456", "Br0C0de" };
//Should be "0, 0, 1, 2, 3, 4, 5, 6"
System.out.println("Sorted string of numbers ->\t" + sortedStringOfNumber(arrayStringData));
}
}
Your solution would run in O(n*log n) mainly due to Arrays.sort.
Use a simple counting sort. This would give you a runtime of O(n).
Look at the string and ignore all other non-digits.
You might also try it this way:
String sortedIntsCsv = Arrays.stream(string).map(s -> s.replaceAll("\\D", "")).mapToInt(Integer::valueOf).sorted().mapToObj(String::valueOf).collect(Collectors.joining(","));

Encode the string using stream api [closed]

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 last year.
Improve this question
I am looking for solution using stream api for below requirement. basically we need to write a encryption logic to convert a string
aaabbbbaae --> a3b4a2e1
Solution without stream's api :
public static void main(String[] args) {
String sampleString = "aaabbbaaaaaee";
char charters[] = sampleString.toCharArray();
char currentChar = charters[0];
char prevChar = charters[0];
int count = 0;
String str = "";
for (char c : charters) {
if(c==currentChar) {
count++;
prevChar = c;
}
else {
str = str + prevChar + count;
currentChar = c;
count=1;
}
}
System.out.println(str+currentChar+count);
}
This would be pretty easy to do yourself
String encryptToLettersAndNumbers(String input) {
String product = "";
char last = input.charAt(0);
int streak = 0;
for(int i = 0; i < input.length(); i++) {
if(input.charAt(i) == last) {
streak++;
} else {
product = product + last + streak;
streak = 1;
last = input.charAt(i);
}
}
product = product + last + streak;
return product;
}
Note that this code is untested. Furthermore this will be a very unsafe method of encryption because h1e1l2o1 is pretty easy to guess.
This should get you started-
String sampleString = "aaabbbaaaaaee";
Arrays.asList(sampleString.chars().mapToObj(c->(char)c).toArray(Character[]::new)).stream().forEach(c->{
//You can put your logic here to process
System.out.print(c);
});
This will convert your String to a Character list and stream through it.

Java basic, reversing a word and how it is achieved through a for loop [closed]

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();
}

Algorithm:Find first non-repeated character in an input string [closed]

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.

Error reversing a string in Java [closed]

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)

Categories