我的泰语字符串是: “หลับตาฝันถึงชื่อเธอ”
我需要像这样输出utf-8编码: “\ u0e08 \ u0e2d \ u0e21 \ u0e40 \ u0e27 \ u0e17 \ u0e22 \ u0e4c \ u0e21 \ u0e2b \ u0e32”
目前,我安装了'iconv'宝石并正在使用
string = Iconv.conv('unicode', 'utf-8', string)
但它不起作用。
invalid encoding ("unicode", "utf-8") (Iconv::InvalidEncoding)
我需要使用Iconv还是编码? (我在Ruby 2.3.1上)
答案 0 :(得分:0)
您最好使用.encode
,它位于标准库中。
自Ruby 1.9.3以来,Iconv已被弃用
但是当我做的时候
"หลับตาฝัน ถึงชื่อเธอ".encode("utf-8")
我得到另一个你想要的结果。
编辑:未在IRB中测试,但在像这样的脚本中测试
# coding: UTF-8
p "หลับตาฝัน ถึงชื่อเธอ".encode("utf-8") # "\u0E2B\u0E25\u0E31\u0E1A\u0E15\u0E32\u0E1D\u0E31\u0E19\u0E16\u0E36\u0E07\u0E0A\u0E37\u0E48\u0E2D\u0E40\u0E18\u0E2D"
你确定你想要的结果吗?
答案 1 :(得分:0)
private String getGiftFinderQuerySet(final GiftFinderForm giftFinderForm)
{
String searchQuery = StringUtils.EMPTY;
final Set<String> giftFinderQuerySet = new LinkedHashSet<String>();
final Set<String> ageSet = giftFinderForm.getAgeSet();
final Set<String> priceSet = giftFinderForm.getPriceSet();
if (giftFinderForm.getGenderSet() != null && !(giftFinderForm.getGenderSet().isEmpty()))
{
final Set<String> genderSet = giftFinderForm.getGenderSet();
for (final String gender : genderSet)
{
final String[] genderList = gender.split(FACET_SEPARATOR);// This will bring first- [sort, bestsellerRating, gender, Female] at one time, then [bestsellerRating, gender, Male] later in the next loop
for (int keyIndex = 0; keyIndex < genderList.length - 1; keyIndex++)
{
if (keyIndex != (genderList.length - 1))
{
keyIndex = keyIndex + keyIndex;
}
final int valueIndex = keyIndex + 1;
giftFinderQuerySet.add(genderList[keyIndex] + FACET_SEPARATOR + genderList[valueIndex]);
}
}
}
if (giftFinderForm.getAgeSet() != null && !(giftFinderForm.getAgeSet().isEmpty()))
{
for (final String age : ageSet)
{
final String[] ageList = age.split(FACET_SEPARATOR);
for (int i = 0; i < ageList.length - 1; i++)
{
if (i != (ageList.length - 1))
{
i = i + i;
}
final int j = i + 1;
giftFinderQuerySet.add(ageList[i] + FACET_SEPARATOR + ageList[j]);
}
}
}
if (giftFinderForm.getPriceSet() != null && !(giftFinderForm.getPriceSet().isEmpty()))
{
for (final String price : priceSet)
{
final String[] priceList = price.split(FACET_SEPARATOR);
for (int i = 0; i < priceList.length - 1; i++)
{
if (i != (priceList.length - 1))
{
i = i + i;
}
final int j = i + 1;
giftFinderQuerySet.add(priceList[i] + FACET_SEPARATOR + priceList[j]);
}
}
}
for (final String query : giftFinderQuerySet)
{
searchQuery = searchQuery.concat(query + FACET_SEPARATOR);
}
searchQuery = searchQuery.substring(0, searchQuery.length() - 1); //Removing the last FACET_SEPARATOR which will be the final query
return searchQuery;
}
您必须强制进行编码。