Friday, July 13, 2018

How do I increment each character in a string using Java?

Problem statement:
You will be given a sentence from from english language. Your job is to increment the letters of the string by an offset of 1. The increment shall be done in a cyclic order i.e. replacement will be as follows:

'a' replaced by 'b', 'b' replaced by 'c' ............. 'z' replaced by 'a'


Method-I:
public class IncrementLetterOfWord {
    public static void main(String args[]) {
        String str = "ABCDEF";
        String res = "";
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            res = res + (char) (c + 1);
        }
        System.out.println(res);
    }
}
Method-II:
public class IncrementLetterByOne {
    public static void main(String args[]) {
        String str = "ABCDEF";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            sb.append((char) (str.charAt(i) + 1));
        }
        System.out.println(sb);
    }
}
Output:
BCDEFG

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...