How to Increment a Variable to the Next or Previous Letter in the Alphabet

How do I increment a variable to the next or previous letter in the alphabet?

One way:

String value = "C";
int charValue = value.charAt(0);
String next = String.valueOf( (char) (charValue + 1));
System.out.println(next);

How to increment letters like numbers in PHP?

Character/string increment works in PHP (though decrement doesn't)

$x = 'AAZ';
$x++;
echo $x; // 'ABA'

Most efficient way to get next letter in the alphabet using PHP

The most efficient way of doing this in my opinion is to just increment the string variable.

$str = 'a';
echo ++$str; // prints 'b'

$str = 'z';
echo ++$str; // prints 'aa'

As seen incrementing 'z' give 'aa' if you don't want this but instead want to reset to get an 'a' you can simply check the length of the resulting string and if its >1 reset it.

$ch = 'a';
$next_ch = ++$ch;
if (strlen($next_ch) > 1) { // if you go beyond z or Z reset to a or A
$next_ch = $next_ch[0];
}

How to increment letters in javascript to next letter?

You could use parseInt with radix 36 and the opposite method Number#toString with the same radix, and a correction for the value.

function nextChar(c) {    var i = (parseInt(c, 36) + 1 ) % 36;    return (!i * 10 + i).toString(36);}
console.log(nextChar('a'));console.log(nextChar('z'));

What is a method that can be used to increment letters?

Simple, direct solution

function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');

As others have noted, the drawback is it may not handle cases like the letter 'z' as expected. But it depends on what you want out of it. The solution above will return '{' for the character after 'z', and this is the character after 'z' in ASCII, so it could be the result you're looking for depending on what your use case is.


Unique string generator

(Updated 2019/05/09)

Since this answer has received so much visibility I've decided to expand it a bit beyond the scope of the original question to potentially help people who are stumbling on this from Google.

I find that what I often want is something that will generate sequential, unique strings in a certain character set (such as only using letters), so I've updated this answer to include a class that will do that here:

class StringIdGenerator {
constructor(chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
this._chars = chars;
this._nextId = [0];
}

next() {
const r = [];
for (const char of this._nextId) {
r.unshift(this._chars[char]);
}
this._increment();
return r.join('');
}

_increment() {
for (let i = 0; i < this._nextId.length; i++) {
const val = ++this._nextId[i];
if (val >= this._chars.length) {
this._nextId[i] = 0;
} else {
return;
}
}
this._nextId.push(0);
}

*[Symbol.iterator]() {
while (true) {
yield this.next();
}
}
}

Usage:

const ids = new StringIdGenerator();

ids.next(); // 'a'
ids.next(); // 'b'
ids.next(); // 'c'

// ...
ids.next(); // 'z'
ids.next(); // 'A'
ids.next(); // 'B'

// ...
ids.next(); // 'Z'
ids.next(); // 'aa'
ids.next(); // 'ab'
ids.next(); // 'ac'

Increment Alphabet characters to next character using JavaScript

Here is an example of a function that loops through all the capital letters of the alphabet, and then increments by one character:

function incrementAlpha() {
var stringOfLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var thisLoopAlpha = "",
AlphaNumber = 1,
NextCode = 0,
NextAlpha = 0,
thisCode = 0;

for (var i=0;i<stringOfLetters.length;i+=1) {
thisLoopAlpha = stringOfLetters[i];
thisCode = thisLoopAlpha.charCodeAt(0);
NextCode = thisCode + 1;
// if Code (Z) then restart at "A"
if (thisCode > 89) {
NextCode = 65;
NextAlpha = String.fromCharCode( NextCode );
} else {
//NextAlpha = "A";
NextAlpha = String.fromCharCode( NextCode );
};

Logger.log('thisCode: ' + thisCode);
Logger.log('NextCode: ' + NextCode);
Logger.log('NextAlpha: ' + NextAlpha + "\n");
};
};

I think that your code should be structured like this:

function onFormSubmit(e) {

//Déclaration des variables
var SheetResponse = SpreadsheetApp.getActiveSheet();
var DerniereLigne = SpreadsheetApp.getActiveSheet().getLastRow();
var DateToday = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'ddMMYY');

//Intégration du suffixe alphabétqiue pour l'ID
// If cells value (A.n)=(A.n-1) then character of cells "N.n" is incremented until "Z" (with n is number of LastRow)
if (SheetResponse.getRange(DerniereLigne,2).getValue() == SheetResponse.getRange(DerniereLigne-1,2).getValue()) {
var AlphaNumber = SheetResponse.getRange(DerniereLigne-1,15).getValue().charCodeAt(0);
var NextCode = AlphaNumber + 1;

// Si Code (Z) alors restart to "A"
if (NextCode > 89) {
nextCode = 65;
var NextAlpha = String.fromCharCode( NextCode );
} else {
// If not cells (N.n) is set to "A"
NextAlpha = "A";
};
}
//Création de l'ID dans la derniére ligne et colonne "N"
SheetResponse.getRange(DerniereLigne,14).setValue(DateToday + NextAlpha);
SheetResponse.getRange(DerniereLigne,15).setValue(NextAlpha);
}

How to increment letters in Python?

This should work:

my_chr = ord(input())
if my_chr == 90:
print('A')
else:
print(chr(my_chr+1))

It takes the input letter (A-Z) and gets its ord() value. It then checks to see if the value is equal to Z (ord('Z') == 90) and prints A otherwise, it increments it by 1 then turns it back to a string and prints it.

How to find out next character alphabetically?

Try this:

char letter = 'c';

if (letter == 'z')
nextChar = 'a';
else if (letter == 'Z')
nextChar = 'A';

else
nextChar = (char)(((int)letter) + 1);

This way you have no trouble when the char is the last of the alphabet.

C# Increment Alphabet character

You cannot modify the value of the first character of str_A1, which is what the ++ operator is doing. Do this instead:

str_B = ((char)(str[0] + 1)).ToString();

Auto increment alphabet in Java?

Yes, you can do it like this:

for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
System.out.println(alphabet);
}

It is also possible with typecasting:

for (int i = 65; i <= 90; i++) {
System.out.println((char)i);
}


Related Topics



Leave a reply



Submit