Create an Array of Characters from Specified Range

Create an array of characters from specified range

Javascript doesn't have that functionality natively. Below you find some examples of how it could be solved:

Normal function, any characters from the base plane (no checking for surrogate pairs)

function range(start,stop) {
var result=[];
for (var idx=start.charCodeAt(0),end=stop.charCodeAt(0); idx <=end; ++idx){
result.push(String.fromCharCode(idx));
}
return result;
};

range('A','Z').join();

The same as above, but as a function added to the array prototype, and therefore available to all arrays:

Array.prototype.add_range = function(start,stop) {
for (var idx=start.charCodeAt(0),end=stop.charCodeAt(0); idx <=end; ++idx){
this.push(String.fromCharCode(idx));
}
return this;
};

[].add_range('A','Z').join();

A range from preselected characters. Is faster than the functions above, and let you use alphanum_range('A','z') to mean A-Z and a-z:

var alphanum_range = (function() {
var data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.split('');
return function (start,stop) {
start = data.indexOf(start);
stop = data.indexOf(stop);
return (!~start || !~stop) ? null : data.slice(start,stop+1);
};
})();

alphanum_range('A','Z').join();

Or any character from the ascii range. By using a cached array, it is faster than the functions that build the array every time.

var ascii_range = (function() {
var data = [];
while (data.length < 128) data.push(String.fromCharCode(data.length));
return function (start,stop) {
start = start.charCodeAt(0);
stop = stop.charCodeAt(0);
return (start < 0 || start > 127 || stop < 0 || stop > 127) ? null : data.slice(start,stop+1);
};
})();

ascii_range('A','Z').join();

Does JavaScript have a method like range() to generate a range within the supplied bounds?

It works for characters and numbers, going forwards or backwards with an optional step.

var range = function(start, end, step) {
var range = [];
var typeofStart = typeof start;
var typeofEnd = typeof end;

if (step === 0) {
throw TypeError("Step cannot be zero.");
}

if (typeofStart == "undefined" || typeofEnd == "undefined") {
throw TypeError("Must pass start and end arguments.");
} else if (typeofStart != typeofEnd) {
throw TypeError("Start and end arguments must be of same type.");
}

typeof step == "undefined" && (step = 1);

if (end < start) {
step = -step;
}

if (typeofStart == "number") {

while (step > 0 ? end >= start : end <= start) {
range.push(start);
start += step;
}

} else if (typeofStart == "string") {

if (start.length != 1 || end.length != 1) {
throw TypeError("Only strings with one character are supported.");
}

start = start.charCodeAt(0);
end = end.charCodeAt(0);

while (step > 0 ? end >= start : end <= start) {
range.push(String.fromCharCode(start));
start += step;
}

} else {
throw TypeError("Only string and number types are supported");
}

return range;

}

jsFiddle.

If augmenting native types is your thing, then assign it to Array.range.

var range = function(start, end, step) {

var range = [];

var typeofStart = typeof start;

var typeofEnd = typeof end;

if (step === 0) {

throw TypeError("Step cannot be zero.");

}

if (typeofStart == "undefined" || typeofEnd == "undefined") {

throw TypeError("Must pass start and end arguments.");

} else if (typeofStart != typeofEnd) {

throw TypeError("Start and end arguments must be of same type.");

}

typeof step == "undefined" && (step = 1);

if (end < start) {

step = -step;

}

if (typeofStart == "number") {

while (step > 0 ? end >= start : end <= start) {

range.push(start);

start += step;

}

} else if (typeofStart == "string") {

if (start.length != 1 || end.length != 1) {

throw TypeError("Only strings with one character are supported.");

}

start = start.charCodeAt(0);

end = end.charCodeAt(0);

while (step > 0 ? end >= start : end <= start) {

range.push(String.fromCharCode(start));

start += step;

}

} else {

throw TypeError("Only string and number types are supported");

}

return range;

}

console.log(range("A", "Z", 1));

console.log(range("Z", "A", 1));

console.log(range("A", "Z", 3));

console.log(range(0, 25, 1));

console.log(range(0, 25, 5));

console.log(range(20, 5, 5));

How to take a range of characters from a character array in Java?

Not sure why you are trying to convert a string to a character array and then concatenate again. As noted by DevilsHnd, you could either split by removing the "Timestamp: " prefix and getting the "Unix time"
or you could replace and then cast. Remember, this assumes that after the replace, user will always have Long numeric value

long lastBlockTime = Long.parseLong(lastBlockTimeAsString.replace("Timestamp: ",""));

String index out of range, converting String array to Char Array

Here is simple program that have array of Strings. First we create counter and take sum of all String.leght() in given array. Then we create Array of char with that length and simply iterate and fill array.

public static void main(String []args){
int index = 0;
String[] ht = new String[3];
int counter = 0;

ht[0] = "Hello";
ht[1] = "World";
ht[2] = "Johm";

for(int i = 0; i < ht.length; i++) {
counter += ht[i].length();

}
char[] keyChar = new char[counter];

for(int i = 0; i < ht.length; i++) {
for (int j = 0; j < ht[i].length(); j++) {
keyChar[index] = ht[i].charAt(j);
index++;
}
}

System.out.println(keyChar);
}

This is solution for your problem.

 public static void main(String[] args) throws FileNotFoundException {
File dataSet = new File("data.txt");
Scanner fileRead = new Scanner(dataSet);
int index = 0;
int index2 = 0;
int tableSize = 128;
String[] ht = new String[tableSize];

while (fileRead.hasNextLine() && index < ht.length) {
ht[index] = fileRead.nextLine();
index++;
}

int counter = 0;

for(int i = 0; i < ht.length; i++) {
counter += ht[i].length();

}
char[] keyChar = new char[counter];

for(int i = 0; i < ht.length; i++) {
for (int j = 0; j < ht[i].length(); j++) {
keyChar[index2] = ht[i].charAt(j);
index2++;
}
}

System.out.println(keyChar);

}

start a char array from a certain index

I created a method for this. This is what it looks like:

public static char[] charIndex(char[] chars, int beginIndex) {
beginIndex--;
char[] result = new char[chars.length - beginIndex];
for(int i = 0; i < chars.length; i++) {
if(!(i < beginIndex)) result[i - beginIndex] = chars[i];
}
return result;
}

Here's how you use it:

char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
System.out.println(Arrays.toString(chars));
chars = charIndex(chars, 2);
System.out.println(Arrays.toString(chars));

The output will be:

[a, b, c, d, e, f, g]
[b, c, d, e, f, g]

How to generate an array of alphabet in jQuery?

You can easily make a function to do this for you if you'll need it a lot

function genCharArray(charA, charZ) {
var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
for (; i <= j; ++i) {
a.push(String.fromCharCode(i));
}
return a;
}
console.log(genCharArray('a', 'z')); // ["a", ..., "z"]

Convert range of a Character[] to String

String has a constructor that takes an array of char, a start and count.

The array will still be (defensively) copied as otherwise mutable state will escape and you will no longer have an immutable String.



Related Topics



Leave a reply



Submit