สมมุติว่าเรามีสตริงตัวเลขเราต้องหาว่าจำนวนนั้นเป็นเลขฐาน B หรือเปล่า? หากสตริงคือ "101110" ให้ b =2 โปรแกรมจะคืนค่าเป็น "จริง" หากสตริงเป็น “A8F” ฐานคือ 16 จะเป็นค่าจริง
วิธีการนั้นง่ายมาก หากอักขระทั้งหมดอยู่ในช่วงสัญลักษณ์ของฐานที่กำหนด ให้คืนค่า จริง หรือ เท็จ
ตัวอย่าง
#include <iostream>
using namespace std;
bool inGivenBase(string s, int base) {
if (base > 16) //program can handle upto base 1
return false;
else if (base <= 10) { //for 0 to 9
for (int i = 0; i < s.length(); i++)
if (!(s[i] >= '0' && s[i] < ('0' + base)))
return false;
} else {
for (int i = 0; i < s.length(); i++)
if (! ((s[i] >= '0' && s[i] < ('0' + base)) || (s[i] >= 'A' && s[i] < ('A' + base - 10))))
return false;
}
return true;
}
int main() {
string str = "A87F";
int base = 16;
if(inGivenBase(str, base)){
cout << str << " is in base " << base;
} else {
cout << str << " is not in base " << base;
}
} ผลลัพธ์
A87F is in base 16