How do I get the last character of a string? - java

How do I get the last character of a string?
public class Main {
public static void main(String[] args) {
String s = "test string";
//char lastChar = ???
}
}

The code:
public class Test {
public static void main(String args[]) {
String string = args[0];
System.out.println("last character: " +
string.substring(string.length() - 1));
}
}
The output of java Test abcdef:
last character: f

Here is a method using String.charAt():
String str = "India";
System.out.println("last char = " + str.charAt(str.length() - 1));
The resulting output is last char = a.

The other answers are very complete, and you should definitely use them if you're trying to find the last character of a string. But if you're just trying to use a conditional (e.g. is the last character 'g'), you could also do the following:
if (str.endsWith("g")) {
or, strings
if (str.endsWith("bar")) {

The other answers contain a lot of needless text and code. Here are two ways to get the last character of a String:
char
char lastChar = myString.charAt(myString.length() - 1);
String
String lastChar = myString.substring(myString.length() - 1);

Try this:
if (s.charAt(0) == s.charAt(s.length() - 1))

Here is a method I use to get the last nth characters of a string:
public static String takeLast(String value, int count) {
if (value == null || value.trim().length() == 0) return "";
if (count < 1) return "";
if (value.length() > count) {
return value.substring(value.length() - count);
} else {
return value;
}
}
Then use it like so:
String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring

Simple solution is:
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
char[] cs = str.toCharArray();
char first = cs[0];
cs[0] = cs[cs.length -1];
cs[cs.length -1] = first;
return new String(cs);
}
Using a character array (watch out for the nasty empty String or null String argument!)
Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
StringBuilder sb = new StringBuilder(str);
char first = sb.charAt(0);
sb.setCharAt(0, sb.charAt(sb.length()-1));
sb.setCharAt(sb.length()-1, first);
return sb.toString();
}
Yet another approach (more for instruction than actual use) is this one:
public String frontBack(String str) {
if (str == null || str.length() < 2) {
return str;
}
StringBuilder sb = new StringBuilder(str);
String sub = sb.substring(1, sb.length() -1);
return sb.reverse().replace(1, sb.length() -1, sub).toString();
}
Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)

public String lastChars(String a) {
if(a.length()>=1{
String str1 =a.substring(b.length()-1);
}
return str1;
}

public char LastChar(String a){
return a.charAt(a.length() - 1);
}

String aString = "This will return the letter t";
System.out.println(aString.charAt(aString.length() - 1));
Output should be:
t
Happy coding!

public char lastChar(String s) {
if (s == "" || s == null)
return ' ';
char lc = s.charAt(s.length() - 1);
return lc;
}

Related

How to write return who letters you should remove to make string palindrome?

Like in question, exercise if it is possible to create a palindromic string of minimum length 3 characters by removing 1 or 2 characters. For example string "abjchba", we can remove letters "jc" and will get palindromic, in this case program should return removed letters so "jc". I know that we can mke palindromic by removing also "ch" but in exercise is that we should remove characters that appear earlier in string. Program should always attempt to create the longest palindromic substring. I wrote methods to reverse String and method to check that string is palindromic:
private static String reverse(String string) {
return new StringBuilder(string).reverse().toString();
}
private static boolean isPalin(String string) {
return string.equals(reverse(string));
}
I also made method to create Palindromic to return symbols we should remove to make palindromic, but beacuse i'm working on sb 'temp' I got exception . Have anyone idea how to fix it and finish exercise?
private static String createPalindrome(String str) {
StringBuilder result = new StringBuilder();
StringBuilder temp = new StringBuilder(str);
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == str.charAt(str.length() - 1 - i)){
continue;
}else {
result.append(str.charAt(i));
temp.deleteCharAt(i);
if (isPalin(temp.toString())){
return result.toString();
}
}
}
return "not possible";
}
Method 1:
Find longest palindromic subsequence(LPS)
Given string: "abjchba"
Longest Palindrome Subsequence: "abhba". Others like "abjba" and "abcba" also are LPS but you want to remove chars that appear earlier so that "abhba".
If (input string length - length of LPS) > 2, return "not possible".
Remove letters from the input string that are not in the LPS.
Start matching string with LPS. 'j' and 'c' won't match. Add them to result and return.
Method 2:
Find longest common subsequence (LCS) between input string and its reverse.
String: "abjchba"
Reverse: "abhcjba"
LCS: Take "abhba" in our case
If (input string length - length of LCS) > 2, return "not possible".
Step 2 will be the same as that of in Method 1 above.
As you are trying for at most 2 deletions, I am thinking if we can do better with time complexity.
I think the simplest way to fix your code is to use recursion. When you find a char that does not match, remove it and call recursively.
// Helper function to remove a character from a string
public static String removeAt(String s, int i)
{
return s.substring(0, i) + s.substring(i + 1);
}
private static String createPalindromeRecursive(String str) {
// Only need to check half the string
for (int i = 0, j = str.length() - 1; i < j; i++, j--) {
// if (something) continue; else {} <- the else is not needed
// because the continue skips to the end of the loop
// or you can negate the condition and don't use continue
if (str.charAt(i) == str.charAt(j)){
continue;
}
String temp = createPalindrome(removeAt(str, i));
// Success. Return the new string
if (null != temp) return temp;
else return null;
}
return str;
}
private static String createPalindrome(String str) {
String palindrome = createPalindromeRecursive(str);
if (palindrome == null || palindrome.length() < str.length() - 2) {
return "not possible";
}
else {
return palindrome;
}
}
using System;
using System.Text;
class MainClass
{
public static String removeAt(String s, int i)
{
return s.Substring(0, i) + s.Substring(i + 1);
}
private static String createPalindromeRecursive(String str)
{
for (int i = 0, j = str.Length - 1; i < j; i++, j--)
{
if (str[i] == str[j])
{
continue;
}
String temp = PalindromeCreator(removeAt(str, i));
if (null != temp) return temp;
else return null;
}
return str;
}
public static string PalindromeCreator(string str)
{
String palindrome = createPalindromeRecursive(str);
StringBuilder result = new StringBuilder();
StringBuilder temp = new StringBuilder(str);
if (palindrome == null || palindrome.Length < str.Length - 2)
{
return "not possible";
}
else
{
for (int i = 0; i < str.Length; i++)
{
if (str[i] == str[(str.Length - 1 - i)])
{
continue;
}
else
{
result.Append(str[i]);
temp.Remove(i, str.Length);
return result.ToString();
}
}
return palindrome;
}
}
static void Main()
{
// keep this function call here
Console.WriteLine(PalindromeCreator(Console.ReadLine()));
}
}

reduce string length when it has pair in java

here it is giving error----required variable ,found value
my code
for eg aabacc when we got any pair like aa remove it from string and the final answer is (ba).
public class Solution {
// Complete the superReducedString function below.
static String superReducedString(String s) {
String sn;
int j=0;
for(int i=0;i<s.length()-1;i++)
{
if(s.charAt(i)!=s.charAt(i+1))
{
sn.charAt(j)=s.charAt(i);
j++;
}
}
return sn;
}
Since String is immutable in Java - String manipulation always generates a new String leaving the previous Strings in String Pool. StringBuffer and StringBuilder are mutable objects and provide methods for String manipulation
Sample working method using StringBuilder is provided below:
static String superReducedString(String s) {
StringBuilder myName = new StringBuilder(s);
int j=0;
for(int i=0;i<s.length()-1;i++) {
if(s.charAt(i)!=s.charAt(i+1)) {
myName.setCharAt(j, s.charAt(i));
j++;
}
}
return myName.toString();
}
You can not do such assignment like sn.charAt(j)=s.charAt(i); since charAt() is function that returns the result, but not a variable. You could use StringBuilder here:
static String superReducedString(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.length() == i+1 || s.charAt(i) != s.charAt(i + 1)) {
sb.append(s.charAt(i));
} else {
i++;
}
}
return sb.toString();
}
s.length() == i+1 checks if it's the last char. In case aabaccr the result will be as expected bar
Just another solution, in case the other answers don't work for you:
static String superReducedString(String s) {
char[] chars = s.toCharArray();
String lastChar = "";
ArrayList<String> newString = new ArrayList<>();
for (char aChar : chars) {
String currentChar = String.valueOf(aChar);
if (lastChar.equals(currentChar))
newString.remove(newString.size() - 1);
else {
newString.add(currentChar);
lastChar = currentChar;
}
}
AtomicReference<String> returnString = new AtomicReference<>("");
newString.forEach(character-> returnString.set(returnString + character));
return returnString.get();
}
The answer is quite simple.
you cannot delete anything from a String but you can move them to another String as you want.
public class Solution {
public static void main(String[] args) {
String s = "abbccd", s1 = "";
if(s.charAt(1) != s.charAt(0))
s1 += s.charAt(0);
if(s.charAt(s.length()-1) != s.charAt(s.length()-2))
s1 += s.charAt(s.length()-1);
for (int i = 1; i < s.length() - 1; i++) {
if (s.charAt(i) != s.charAt(i - 1) && s.charAt(i) != s.charAt(i + 1))
s1 += s.charAt(i);
}
System.out.println(s1);
}
}
You create another String.
Then in a for loop iterating from 1 (NOT 0) to s.length()-1 (NOT s.length()), you check if the s.charAt(i) (current character) is equal to the preceding or following one. If it's not equal to any of them, you add it to the second String and then you print it. We are checking both sides so that's why the loop is from 1 to s.length()-1, to avoid out of bounds exceptions.
EDIT: to check the first and last character.

How to return string with all instances of a string replaced by another string ( Java )

In this program, I am trying to return a new string that is composed of new letters that were added and old letters if the didn't fit the constraints. I am stuck in terms of I don't know how to fix my code so that it prints correctly. Any help or suggestions is greatly appreciated!
Here are some examples:
str: "asdfdsdfjsdf", word: "sdf", c: "q"
should return "aqdqjq", I'm getting "asdqqq"
str: "aaaaaaaa", word: "aaa", c: "w"
should return "wwaa", as of right now my code only returns "ww"
public static String replaceWordWithLetter(String str, String word, String c)
String result = "";
int index = 0;
while (index < str.length() )
{
String x = str.substring(index, index + word.length() );
if (x.equals(word))
{
x = c;
index = index + word.length();
}
result = result + x;
index++;
}
if (str.length() > index)
{
result = result + str.substring(index, str.length() - index);
}
return result;
}
You seem to be overcomplicating this. You can simply use the replace() method:
public static String replaceWordWithLetter(String str, String word, String c) {
return str.replace(word, c);
}
Which when called as:
replaceWordWithLetter("asdfdsdfjsdf", "sdf", "q")
Produces the output:
aqdqjq
The problem with your current method is that if the substring is not equal to word, then you will append as many characters as there are in word, and then only move up one index. If you will not be replacing the sequence, then you only need to append one character to result. Also it is much more efficient to use a StringBuilder. Also as noted if the String is not divisible by word.length(), this will throw a StringIndexOutOfBoundsError. To solve this you can use the Math.min() method to ensure that the substring does not go out of bounds. Original method with fixes:
public static String replaceWordWithLetter(String str, String word, String c) {
StringBuilder result = new StringBuilder();
int index = 0;
while (index < str.length() )
{
String x = str.substring(index, Math.min(index + word.length(), str.length()));
if (x.equals(word))
{
result.append(c);
index = index + word.length();
}
//If we aren't replacing, only add one char
else {
result.append(x.charAt(0));
index++;
}
}
if (str.length() > index)
{
result.append(str.substring(index, str.length() - index));
}
return result.toString();
}
Found the fix to my issue using #GBlodgett's code:
String result = "";
int index = 0;
while (index <= str.length() - word.length() )
{
String x = str.substring(index, index + word.length() );
if (x.equals(word))
{
result = result + c;
index = index + word.length();
}
else {
result = result + x.charAt(0);
index++;
}
}
if (str.length() < index + word.length())
{
result = result + (str.substring(index));
}
return result;
}
You can use String.replaceAll() method.
example:
public class StringReplace {
public static void main(String[] args) {
String str = "aaaaaaaa";
String fnd = "aaa";
String rep = "w";
System.out.println(str.replaceAll(fnd, rep));
System.out.println("asdfdsdfjsdf".replaceAll("sdf", "q"));
}
}
Output:
wwaa
aqdqjq

How to switch two characters in a string?

Given a string as input, return the string with its last 2 chars swapped. And, if the string has less than 2 chars, do nothing and return the input string.
Here is the code I wrote so far:
public class SwapLastChars {
static String testcase1 = "Hello";
public static void main(String args[]) {
SwapLastChars testInstance = new SwapLastChars();
String result = testInstance.swap(testcase1);
System.out.println(result);
}
public String swap(String str1) {
String str = "";
int length = str1.length();
char last = str1.charAt(length - 1);
char l = str1.charAt(length - 2);
if (length == 1)
return str1;
for (int i = 0; i < str1.length() - 2; i++) {
str = str + str1.charAt(i);
}
str = str + last + l;
return str;
}
}
Problem is in my test cases,any help?
Testcase Pass/Fail Parameters Actual Output Expected Output
1 pass 'aabbccdd' aabbccdd aabbccdd
2 fail 'A' null A
3 pass 'hello' helol helol
If you pass "A" you'll get StringIndexOutOfBoundsException rather than null. Unless you suppress it in a catch clause and return null.
Quick fix. Move the length check to start of the method. That should solve your issue.
public class SwapLastChars {
static String testcase1 = "A";
public static void main(String args[]) {
SwapLastChars testInstance = new SwapLastChars();
String result = testInstance.swap(testcase1);
System.out.println(result);
}
public String swap(String str1) {
if(str1 == null || str1.length() < 2) { //Move here
return str1;
}
String str = "";
int length = str1.length();
char last = str1.charAt(length - 1);
char l = str1.charAt(length - 2);
for(int i = 0; i < str1.length() - 2; i++) {
str = str + str1.charAt(i);
}
str = str + last + l;
return str;
}
}
You should check for length at the very beginning of your function.
public String swap(String str1){
String str="";
int length=str1.length();
if (length <=2)
return str1;
char last=str1.charAt(length-1);
char l=str1.charAt(length-2);
for(int i=0;i<str1.length()-2;i++)
{
str=str+str1.charAt(i);
}
str=str+last+l;
return str;
}
I know this has already been answered, but I feel OPs swap method can be simplified by using a StringBuilder:
public static String swap(String word) {
//Answer by Syam
if (word == null || word.length() < 2) {
return word;
}
//Create new StringBuilder
StringBuilder s = new StringBuilder(word);
//Get second last char
char c = s.charAt(s.length() - 2);
//Replace second last char with last char
s.setCharAt(s.length() - 2, s.charAt(s.length() - 1));
//replace last char with stored char
s.setCharAt(s.length() - 1, c);
return s.toString();
}
Run:
System.out.println(swap("aabbccdd"));
System.out.println(swap("A"));
System.out.println(swap("hello"));
Output:
aabbccdd
A
helol
And here is why

Write a method to replace all spaces in a string with '%20'?

I have a question about a programming problem from the book Cracking The Code Interview by Gayl Laakmann McDowell, 5th Edition.
I'm not sure what is wrong with my answer? It varies a lot from the answer given in the book.
public String replace(String str){
String[] words = str.split(" ");
StringBuffer sentence = new StringBuffer();
for(String w: words){
sentence.append("%20");
sentence.append(w);
}
return sentence.toString();
}
Question in the book says:
Note: if implementing in Java, please use a character array so that
you can perform this operation in place.
It also says that the char array that you get as input is long enough to hold the modified string.
By using split and StringBuffer you use additional O(n) space. That's why your answer varies a lot and is incorrect (apart from adding additional "%20").
In this loop, the program adds %20 before each word:
for(String w: words){
sentence.append("%20");
sentence.append(w);
}
That will produce incorrect results, for example for a b it will give %20a%20b.
There's a much simpler solution:
public String replace(String str) {
return str.replaceAll(" ", "%20");
}
Or, if you really don't want to use .replaceAll, then write like this:
public String replace(String str) {
String[] words = str.split(" ");
StringBuilder sentence = new StringBuilder(words[0]);
for (int i = 1; i < words.length; ++i) {
sentence.append("%20");
sentence.append(words[i]);
}
return sentence.toString();
}
You can also do the following, which replaces any space
String s = "Hello this is a string!";
System.out.println(replaceSpace(s, "%20"));
public static String replaceSpace(String s, String replacement) {
String ret = s.replaceAll(" *", replacement);
return ret;
}
Gives
Hello%20this%20is%20a%20string!
One of the simplest way:
public void replaceAll( String str )
{
String temp = str.trim();
char[] arr = temp.toCharArray();
StringBuffer sb = new StringBuffer();
for( int i = 0; i < arr.length; i++ )
{
if( arr[i] == ' ' )
{
sb.append( "%20" );
}
else
{
sb.append( arr[i] );
}
}
}
private static String applyReplaceOperationWithCount(String str) {
if (StringUtils.isEmpty(str)) { //if string is null or empty, return it
return str;
}
char[] strChar = str.toCharArray();
int count = 0; //count spaces in the string to recalculate the array length
for (char c : strChar) {
if (c == ' ') {
count++;
}
}
if (count == 0) { // if there are no spaces in the string, return it
return str;
}
int length = strChar.length;
char[] newChar = new char[length + (count * 2)]; // 1 char will be replaced by 3 chars. So the new length should be count*2 larger than original
int index = 0;
for (char c : strChar) {
if (c != ' ') { // if char is not a space just push it in the next available location
newChar[index++] = c;
} else { // if char is a space just push %,2,0
newChar[index++] = '%';
newChar[index++] = '2';
newChar[index++] = '0';
}
}
return new String(newChar); // convert the new array into string
}
I am using matches and replaceAll it works well.
public class ReplaceSpaces {
public static void main(String[] args) {
String text = " Abcd olmp thv ";
if(text.matches(".*\\s+.*")){
System.out.println("Yes I see white space and I am replacing it");
String newText = text.replaceAll("\\s+", "%20");
System.out.println(newText);
}
else{
System.out.println("Nope I dont see white spaces");
}
}
}
Output
Yes I see white space and I am replacing it
%20Abcd%20olmp%20thv%20
public static String replaceSpaceInString(String string,String toreplace){
String replacedString = "";
if(string.isEmpty()) return string;
string = string.trim();
if(string.indexOf(" ") == -1)return string;
else{
replacedString = string.replaceAll("\\s+",toreplace);
}
return replacedString;
}

Categories