I think theres something wrong with my syntax. So please help me with those syntax:
public class Main {
public static void main(String arg[]) {
String number = "1234";
System.out.println("original String: " + number);
String reversed = inPlaceReverse(number);
System.out.println("reversed String: " + reversed);
}
public String inPlaceReverse(final String input) {
final StringBuilder builder = new StringBuilder(input);
int length = builder.length();
for (int i = 0; i < length / 2; i++) {
final char current = builder.charAt(i);
final int otherEnd = length - i - 1;
builder.setCharAt(i, .charAt(otherEnd)); // swap
builder.setCharAt(otherEnd, current);
}
return builder.toString();
}
}
Reverse function is not working properly.
StringBuilder has a function that does this:
StringBuilder.reverse() You can also append .toString() to this call to get it back into a String.
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#reverse()
There were some errors in your code.
1) error: illegal start of expression builder.setCharAt(i, .charAt(otherEnd));
correction: builder.setCharAt(i, **builder**.charAt(otherEnd));
2) error: non-static method inPlaceReverse(String) cannot be referenced from a static context
This is because you have declared main() as static whereas your isPlaceReverse() is non-static. You cannot reference a non-static member within a static member.
Change your function definition to public **static** String inPlaceReverse(final String input)
After you make the above corrections, you'll get the desired output:
public class Main {
public static void main(String args[]) {
String number = "1234";
System.out.println("original String: " + number);
String reversed = inPlaceReverse(number);
System.out.println("reversed String: " + reversed);
}
public static String inPlaceReverse(final String input) {
final StringBuilder builder = new StringBuilder(input);
int length = builder.length();
for (int i = 0; i < length / 2; i++) {
final char current = builder.charAt(i);
final int otherEnd = length - i - 1;
builder.setCharAt(i, builder.charAt(otherEnd)); // swap
builder.setCharAt(otherEnd, current);
}
return builder.toString();
}
}
Output
original String: 1234
reversed String: 4321
Update your reverse logic to :
public static String inPlaceReverse(final String input) {
final StringBuilder builder = new StringBuilder(input);
int length = builder.length();
for (int i = 0; i < length / 2; i++) {
final char current = builder.charAt(i);
final char otherEnd = builder.charAt(length - i - 1);
builder.setCharAt(i, otherEnd); // swap
builder.setCharAt(length-i-1, current);
}
return builder.toString();
}
A more appropriate way will be:
public static String inPlaceReverse(final String input) { // make it static
final StringBuilder builder = new StringBuilder(input);
return builder.reverse().toString();
}
Related
I'm going bonkers on my java assignment. I'm rather new to methods and I can't seem to get my head around this one. Could you perhaps give me a guiding hand?
I'm trying to convert an array of int to a string and print it using the. toString method. We are not allowed to use some libraries though. All I get from my code is a 'stack overflow'...
Code:
public static void main(String[] args) {
int[] arr = {3,4,5,6,7};
String str = toString(arr);
System.out.println("arr = " + str);
}
private static String toString(int[] arr) {
String str = Arrays.toString(arr);
return str;
}
This is the complete code of my program so far:
public class Arrays {
public static void main(String[] args) {
int[] arr = {3,4,5,6,7};
int result = sum(arr);
System.out.println(result);
String str = toString(arr);
System.out.println("arr = " + str);
}
private static int sum(int[] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++) {
result += arr[i];
}
return result;
}
private static String toString(int[] arr) {
String str = Arrays.toString(arr);
return str;
}
}
The result in my console:
25
Exception in thread "main" java.lang.StackOverflowError
at tb222kc_lab3.Arrays.toString(Arrays.java:24)
at tb222kc_lab3.Arrays.toString(Arrays.java:24)
at tb222kc_lab3.Arrays.toString(Arrays.java:24).....
Change your Arrays.toString(arr) in toString Method to java.util.Arrays.toString(arr)
Your code has gone into recursive call because you have named your class as Arrays
Then I will create my own toString like this :
public String toString(int[] arr) {
StringBuilder result = new StringBuilder();
result.append("[");
for (int a : arr) {
result.append(a);
}
result.append("]");
return result.toString();
}
Your toString() method should look like this:
private static String toString(int[] arr) {
String str = "[";
for (int index = 0; index < arr.length; index++) {
// Concat the string with the int value.
str += arr[index];
// Add delimiter only if we're not at the last index.
if (index < arr.length - 1) {
str += ", ";
}
}
str += "]";
return str;
}
I will only add to this that college professors are notorious for giving their students requirements that have no bearing on real life (like don't use libraries).
Assuming I have a string foo = "This is an apple"
The Unicode code point equivalent will be
" \\x74\\x68\\x69\\x73.......... \\x61\\x70\\x70\\x6c\\x65 "
T h i s ............. a p p l e
How do I convert from String foo
to
String " \\x74\\x68\\x69\\x73.......... \\x61\\x70\\x70\\x6c\\x65 "
try this..
public static String generateUnicode(String input) {
StringBuilder b = new StringBuilder(input.length());
for (char c : input.toCharArray()) {
b.append(String.format("\\u%04x", (int) c));
}
return b.toString();
}
Here a working code snippet to make the conversion:
public class HexTest {
public static void main(String[] args) {
String testStr = "hello日本語 ";
System.out.println(stringToUnicode3Representation(testStr));
}
private static String stringToUnicode3Representation(String str) {
StringBuilder result = new StringBuilder();
char[] charArr = str.toCharArray();
for (int i = 0; i < charArr.length; i++) {
result.append("\\u").append(Integer.toHexString(charArr[i] | 0x10000).substring(1));
}
return result.toString();
}
}
That display:
\u0068\u0065\u006c\u006c\u006f\u65e5\u672c\u8a9e\u0020
If you want to get rid of the extra zeros you elaborate it as described here.
Here another version to do the conversion, by passing "This is an apple" you get
\u54\u68\u69\u73\u20\u69\u73\u20\u61\u6e\u20\u61\u70\u70\u6c\u65
by using:
private static String str2UnicodeRepresentation(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
int cp = Character.codePointAt(str, i);
int charCount = Character.charCount(cp);
//UTF characters may use more than 1 char to be represented
if (charCount == 2) {
i++;
}
result.append(String.format("\\u%x", cp));
}
return result.toString();
}
Is it possible to use substring to extract single utf8 kanji from a string? The problem is that utf-8 "characters" can have a length of 1, 2 or 3.
For instance, length of "𨦇𨦈𥻘" is 6 so String.substring(1, 2) doesn't get the first complete character.
In PERL, I could just use substr("𨦇𨦈𥻘", 1, 1) to get the first character, or substr("𨦇𨦈𥻘", 2, 1) to get the second character.
UPDATE:
Based on #msandiford's suggestion, I came up with this.
public class SplitKanji {
private String [] splitKanji;
private SplitKanji(String string) {
int cpCount = string.codePointCount(0, string.length());
splitKanji = new String[cpCount];
int nextSlot = 0;
for (int i = 0; i < string.length();) {
int ii = string.offsetByCodePoints(i, 1);
splitKanji[nextSlot++] = string.substring(i, ii);
i = ii;
}
}
private String[] get() {
return splitKanji;
}
public static void main(String[] args) {
String startKanji = "私今日𨦇𨦈𥻘";
SplitKanji myStuff = new SplitKanji(startKanji);
String [] split = myStuff.get();
System.out.print(startKanji + "=");
for(String kanji: split)
System.out.print(kanji + ":" + kanji.length() + ", ");
System.out.println();
}
}
You can extract individual Unicode codepoints from the String like so:
public static final String KANJI = "𨦇𨦈𥻘";
public static void main(String[] args)
{
System.out.println(KANJI.length()); // 6
System.out.println(KANJI.codePointCount(0, KANJI.length()));// 3
// Loop over each code point
for (int i = 0; i < KANJI.length(); )
{
System.out.println(KANJI.codePointAt(i));
i = KANJI.offsetByCodePoints(i, 1);
}
// Extract the third codepoint
int indexForThirdCodePoint = KANJI.offsetByCodePoints(0, 2);
int thirdCodePoint = KANJI.codePointAt(indexForThirdCodePoint);
System.out.println(thirdCodePoint);
// Convert codepoint back to string
System.out.println(new String(Character.toChars(thirdCodePoint)));
}
You could use the above techniques to obtain the start and end index of the codepoint that you require, and then use substring(start, end) to extract.
(edit) All of this could be simplified with a bit of judicious refactoring and utility functions. Below is one possible example; I don't know the use case for your code is, so it's a bit hard to know what would be best for you.
public static final String KANJI = "𨦇𨦈𥻘";
public static int lengthCodepoints(String s)
{
return s.codePointCount(0, s.length());
}
public static String substringCodepoint(String s, int startCodepoint, int numCodepoints)
{
int startIndex = s.offsetByCodePoints(0, startCodepoint);
int endIndex = s.offsetByCodePoints(startIndex, numCodepoints);
return s.substring(startIndex, endIndex);
}
public static void main(String[] args)
{
int cpLength = lengthCodepoints(KANJI);
for (int i = 0; i < cpLength; ++i)
{
System.out.println(substringCodepoint(KANJI, i, 1));
}
}
I'm trying to do a simple reverse task like: change the string "how are you" to "you are how".
this is my code:
public class Program {
public static String revSentence (String str) {
String [] givenString = str.split(" ");
String [] retString = new String[givenString.length];
int last = givenString.length - 1;
for (int i = 0; i < givenString.length; i++) {
retString [i] = givenString[last--];
}
return retString.toString();
}
public static void main(String[] args) {
String m = "how are you";
System.out.println(revSentence(m));
}
}
I'm getting a weird output:
[Ljava.lang.String;#e76cbf7
The output isn't "weird" at all - it's the Object's internal string representation, created by Object.toString(). String[] doesnt override that. If you want to output all entires, loop through them and concatenate them, Best using a StringBuilder to avoid creating unnecessary String instances.
public static String arrayToString (String[] array) {
StringBuilder result = new StringBuilder();
for (String value : array) {
result.append(value);
}
return StringBuilder.toString();
}
If you don'T need that method on it'S own and want to include it in the overall process of reversing the sentence, this is how it may look. It iterates only once, iterating backwards (= counting down) to reverse the sentence.
public static String revSentence (String str) {
String [] givenString = str.split(" ");
StringBuilder result = new StringBuilder();
// no need for 'last', we can use i to count down as well...
for (int i = givenString.length - 1 ; i >= 0; i--) {
result.append(givenString[i]);
}
return result.toString();
}
[Edit]: because of the OPs comment to one of the other answers, about not having learned how to use StringBUilder yet, here is a arrayToStirng method without using one. Note however that this should not be done normally, as it creates useless instances of String whiche are not cleaned up by the GC because of the immutable nature of String(all instances are kept for reuse).
public static String arrayToString (String[] array) {
String result = "";
for (String value : array) {
result += value;
}
return result;
}
Or, without a dedicate arrayToString method:
public static String revSentence (String str) {
String [] givenString = str.split(" ");
String result = "";
for (int i = givenString.length-1 ; i >= 0 ; i--) {
result += givenString[i];
}
return result;
}
Here is a solution:
public class Program {
public static String revSentence (String str) {
String retString = "";
String [] givenString = str.split(" ");
for (int i=givenString.length-1; i>=0; i--) {
retString += givenString[i] + " ";
}
return retString;
}
public static void main(String[] args) {
String m = "how are you";
System.out.print(revSentence(m));
}
}
Modified it to make the "revSentence" function return a String, plus improved the code a bit. Enjoy!
Calling toString() on an array object (in your case retString) doesn't print all array entries, instead it prints object address.
You should print array entries by iterating over them.
Use this code for reversed string
StringBuilder builder = new StringBuilder();
for(String s : retString) {
builder.append(s);
}
return builder.toString();
Calling toString on an array gives you the memory ref which isn't very useful. Try this:
public static String revSentence (String str) {
String[] givenString = str.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = givenString.length - 1; i >= 0; i--) {
sb.append(givenString[i]);
if (i != 0)
sb.append(" ");
}
return sb.toString();
}
the for loop start from greater length to lower and builder.append(givenString[i] + " "); this will concatenate String and return whole sentence you are how you could use both mySentence += givenString[i] + " "; or builder.append(givenString[i] + " "); but the best way is to use StringBuilder class (see docs)
public class Program {
public static String revSentence(String str) {
String[] givenString = str.split(" ");
String[] retString = new String[givenString.length];
int last = givenString.length - 1;
//String mySentence = "";
StringBuilder builder = new StringBuilder();
for (int i = givenString.length - 1; i >= 0; i--) {
// retString [i] = givenString[i];
// mySentence += givenString[i] + " ";
builder.append(givenString[i] + " ");
}
return builder.toString(); // retuning String
//return mySentence;
}
public static void main(String[] args) {
String m = "how are you";
System.out.println(revSentence(m));
}
}
Faster, and shorter:
To reverse a word, use:
public String reverseWord(String s) {
StringBuilder y = new StringBuilder(s);
return y.reverse();
}
Now split and use this method and use Stringbuidler.append to concatenate the all.
And dont forget the space inbetween.
I am trying to solve the following problem but how do write the method that accepts String as an argument?
Write a method named printReverse that accepts a String as an
argument and prints the characters in the opposite order. If the empty
string is passed as an argument, the method should produce no output.
Be sure to write a main method that convincingly demonstrates your
program in action. Do not use the reverse method of the
StringBuilder or StringBuffer class!
So far I have solved it in a easier manner:
import java.util.Scanner;
class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: " + reverse);
}
}
I highly recommend you to go through a basic tutorial.
You can simply do:
private static String myReverse(String str) {
String reverse = "";
int length = str.length();
for( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + str.charAt(i);
}
return reverse;
}
And in your main, you simply:
String reversed = myReverse(in.nextLine());
Note that the method is static because you're referring to it from a static manner (main method). If you don't want it to be static, you'll have to access it via an object.
Also note that it's a good practice to always have curly brackets for for loops, even if it contains a single line.
how do write the method that accepts String as an argument?
public static String reverse(String forward) {
char[] strChar = forward.toCharArray();
String reverse = "";
for( int i = strChar.length - 1 ; i >= 0 ; i-- )
reverse = reverse + strChar[i];
return reverse;
}
But for large string appending character with + operator can be inefficient. And reversing string with above approach will result in wrong for uni-code mismatches. As it reverse the code units but not character. There is actually a built-in support available to reverse a string using StringBuilder which works correctly:
public static String reverse(String forward) {
StringBuilder builder = new StringBuilder(forward);
String reverse = builder.reverse().toString();
return reverse;
}
Something like this:
public class StringUtils {
public static String reverse(String forward) {
String result = "";
// Put your code here
return result;
}
}
Using Java 9 you can implement something like this. This code works with both regular characters and surrogate pairs:
public static void printReverse(String str) {
// character code points
str.codePoints()
// character as string
.mapToObj(Character::toString)
// concatenate in reverse order
.reduce((a, b) -> b + a)
// output
.ifPresent(System.out::println);
}
public static void main(String[] args) {
// regular characters
printReverse("lorem ipsum");
// surrogate pairs
printReverse("\uD835\uDD43\uD835\uDD46R\uD835\uDD3C\uD835\uDD44" +
" \uD835\uDD40P\uD835\uDD4A\uD835\uDD4C\uD835\uDD44");
}
Output:
muspi merol
𝕄𝕌𝕊P𝕀 𝕄𝔼R𝕆𝕃
See also: Is there any other way to remove all whitespaces in a string?
Try this:
private static String reverseString(String str) {
String revString = "";
for (int i = str.length() - 1; i >= 0; i--) {
revString = revString + str.charAt(i);
}
return revString;
}
package dowhile;
public class Dowhile {
public static void main(String[] args) {
// TODO code application logic here
String message = "i love java programming";
int msglength = message.length();
int index = msglength - 1;
while (index >= 0) {
System.out.print(message.charAt(index));
index--;
}
}
}
Output:
gnimmargorp avaj evol i
private static void printReverse(String org) {
StringBuffer buffer = new StringBuffer(org);
String reversedStr = buffer.reverse().toString();
System.out.println("The reverse of the string \""
+ str + "\" is \"" + reversedStr + "\".");
}
in the main call the function
printReverse(original);