GVKun编程网logo

将String转换为int。如果String为null,则将int设置为0(将string转化为int)

8

此处将为大家介绍关于将String转换为int。如果String为null,则将int设置为0的详细内容,并且为您解答有关将string转化为int的相关问题,此外,我们还将为您介绍关于c++不能将s

此处将为大家介绍关于将String转换为int。如果String为null,则将int设置为0的详细内容,并且为您解答有关将string转化为int的相关问题,此外,我们还将为您介绍关于c + +不能将string转换为wstring、c – 使用boost spirit将String转换为int、c# – 重新解释将数组从string转换为int、Hive where int/string <> int/int/string <> string cast类型转化/where自动过滤掉NULL,保留‘‘的有用信息。

本文目录一览:

将String转换为int。如果String为null,则将int设置为0(将string转化为int)

将String转换为int。如果String为null,则将int设置为0(将string转化为int)

我有一个将Android数据保存在其中的函数,sqlite但必须将String数据转换为Integer

只要Stringnull我想保存为0

以下是我的代码,只要值是 null

 int block_id = Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id"));

block_id上述转化为Integer

这是我决定要执行的操作,但是仍然无法将字符串值转换为0每当它的null

int block_id = Converttoint(jsonarray.getJSONObject(i).getString("block_id"));

然后功能 convertToInt

 public static Integer convertToInt(String str) {    int n=0;  if(str != null) {      n = Integer.parseInt(str);  }    return n;}

我应该如何对其进行更改以使其起作用?

答案1

小编典典

不用编写自己的函数,而是使用try-catch的内部构造。您的问题是,jsonarrayor
jsonarray.getJSONObject(i)或值本身是a,null并且您在null引用上调用方法。请尝试以下操作:

int block_id = 0;        //this set''s the block_id to 0 as a default.try {    block_id =  Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id"));    //this will set block_id to the String value, but if it''s not convertable, will leave it 0.} catch (Exception e) {};

在Java中,异常用于标记意外情况。例如,将非数字解析为数字StringNumberFormatException)或在null引用上调用方法(NullPointerException)。您可以通过多种方式捕获它们。

try{    //some code} catch (NumberFormatException e1) {    e.printStackTrace()     //very important - handles the Exception but prints the information!} catch (NullPointerException e2) {    e.printStackTrace();}

或利用事实,它们都可以扩展Exception

try {    //somecode} catch (Exception e) {    e.printStackTrace;};

或从Java 7开始:

try {    //somecode} catch (NullPointerException | NumberFormatException e) {    e.printStackTrace;};

注意

我相信您会仔细阅读答案,请记住,在StackOverflow上,我们需要最小,完整和可验证的示例,其中包括您的异常的StackTrace。就您而言,它可能始于以下内容:

Exception in thread "main" java.lang.NullPointerException

然后,调试会容易得多。没有它,这只是猜测。

编辑: 根据公认的答案

接受的答案很好,并且可以使用,只要用key:存储的值block_id是数字即可。如果不是数字,您的应用程序将崩溃。

代替:

JSONObject jObj = jsonarray.getJSONObject(i);int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;

一个应该使用:

int block_id;try{    JSONObject jObj = jsonarray.getJSONObject(i);    block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;} catch (JSONException | NullPointerException e) {    e.printStackTrace();}

c + +不能将string转换为wstring

c + +不能将string转换为wstring

我想将一个stringvariables转换为wstring由于一些德语字符在variables上执行substr时会导致问题。 当这些特殊字符出现之前,起始位置就是伪造的。 (例如:对于“ä”大小()返回2而不是1)

我知道以下转换工作:

wstring ws = L"ä";

因为,我想转换一个variables,我想知道是否有一个替代方式,如

wstring wstr = L"%s"+str //this is Syntaxically wrong,but wanted sth alike

除此之外,我已经尝试了下面的例子将string转换为wstring:

无法通过PowerShell在文本文件中使用加号“+”来编辑/replacestring值

如何将回车作为字符添加到文件?

什么是Windows环境variables名称和值的有效字符?

如何在批处理中的echo命令中使用重音字符?

Windows资源pipe理器使用的sorting顺序中的第一个字符是什么?

string foo("ä"); wstring_convert<codecvt_utf8<wchar_t>> converter; wstring wfoo = converter.from_bytes(foo.data()); cout << foo.size() << endl; cout << wfoo.size() << endl;

,但我得到像这样的错误

'wstring_convert' was not declared in this scope

我使用的是Ubuntu 14.04,我的main.cpp是用cmake编译的。 谢谢你的帮助!

我应该如何传递密码(包含特殊字符)作为命令行参数?

用linux sedreplace带有特殊字符的string

用fprintf发送一个箭头键

Windows命令行和batch file:文件名中未转义的特殊字符的潜在问题?

这个字符有什么区别?

“hahakubile”的解决方案为我工作:

std::wstring s2ws(const std::string& s) { std::string curLocale = setlocale(LC_ALL,""); const char* _Source = s.c_str(); size_t _Dsize = mbstowcs(NULL,_Source,0) + 1; wchar_t *_Dest = new wchar_t[_Dsize]; wmemset(_Dest,_Dsize); mbstowcs(_Dest,_Dsize); std::wstring result = _Dest; delete []_Dest; setlocale(LC_ALL,curLocale.c_str()); return result; }

但是,返回值不是100%正确的:

string s = "101446012MaßnStörfall PAt #Maßnahme Störfall 00810000100121000102000020100000000000000"; wstring ws2 = s2ws(s); cout << ws2.size() << endl; // returns 110 which is correct wcout << ws2.substr(29,40) << endl; // returns #Ma nahme St rfall with symbols

我想知道为什么用符号代替德文字符。

再次感谢!

如果您使用Windows / Visual Studio并需要将字符串转换为wstring,则应使用:

#include <AtlBase.h> #include <atlconv.h> ... string s = "some string"; CA2W ca2w(s.c_str()); wstring w = ca2w; printf("%s = %ls",s.c_str(),w.c_str());

将wstring转换为字符串的相同过程(有时您需要指定一个代码页 ):

#include <AtlBase.h> #include <atlconv.h> ... wstring w = L"some wstring"; CW2A cw2a(w.c_str()); string s = cw2a; printf("%s = %ls",w.c_str());

你可以指定一个代码页 ,甚至UTF8(使用JNI / Java时,这是相当不错的)。

CA2W ca2w(str,CP_UTF8);

如果您想了解更多关于代码页的信息 ,可以参阅关于Joel on Software的一篇有趣的文章: 绝对最小化每个软件开发人员绝对肯定必须了解Unicode和字符集 。

这些CA2W(将Ansi转换为Wide = unicode)宏是ATL和MFC字符串转换宏的一部分 ,包括样本。

有时你需要禁用安全警告#4995',我不知道其他解决方法(对于我在VS2012中编译WindowsXp时发生的)。

#pragma warning(push) #pragma warning(disable: 4995) #include <AtlBase.h> #include <atlconv.h> #pragma warning(pop)

编辑:好吧,根据这篇文章,Joel的文章似乎是:“而娱乐,实际技术细节上很轻。 文章: 每个程序员绝对,积极需要知道编码和字符集与文本工作 。

重点是这个

string foo("ä")

已经是一个错误。 从这里开始阅读所有答案。 而且要小心, 一个是非常错误的:)

c – 使用boost spirit将String转换为int

c – 使用boost spirit将String转换为int

我听说精神在将字符串转换为int时非常快.

但是我无法创建一个可以这样做的简单函数.就像是

int string_to_int(string& s){
     / * * ????? /
}

任何人都可以使用提升精神来填补这个功能.

顺便说一句,我正在使用boost 1.34而不是最新版本.

解决方法

有几种方法可以实现这一目标:

#include <boost/spirit/include/qi_parse.hpp>
#include <boost/spirit/include/qi_numeric.hpp>

namespace qi = boost::spirit::qi;

std::string s("123");
int result = 0;
qi::parse(s.begin(),s.end(),qi::int_,result);

或更短:

#include <boost/spirit/include/qi_parse.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/qi_auto.hpp>    
namespace qi = boost::spirit::qi;

std::string s("123");
int result = 0;
qi::parse(s.begin(),result);

这是基于Spirit的自动功能.如果将其中一个包装成一个函数,就可以得到你想要的东西.

编辑:我现在才看到你正在使用Boost 1.34.所以这里有相应的咒语:

#include <boost/spirit.hpp>

using namespace boost::spirit;

std::string s("123");
int result = 0;
std::string::iterator b = s.begin();
parse(b,int_p[assign_a(result)]);

c# – 重新解释将数组从string转换为int

c# – 重新解释将数组从string转换为int

我想在int数组中重新解释一个字符串,其中每个int根据处理器架构负责4或8个字符.

有没有办法以相对便宜的方式实现这一目标?
我试过这个,但似乎没有在一个int中重新解释4个字符

string text = "abcdabcdefghefgh";

unsafe
{
    fixed( char* charPointer = text )
    {
        Int32* intPointer = (Int32*)charPointer;

        for( int index = 0; index < text.Length / 4; index++ )
        {
            Console.WriteLine( intPointer[ index ] );
        }
    }
}

解决方案:(根据您的需要更改Int64或Int32)

string text = "abcdabcdefghefgh";

unsafe
{
    fixed( char* charPointer = text )
    {
            Int64* intPointer = (Int64*)charPointer;
            int conversionFactor = sizeof( Int64 ) / sizeof( char );

            int index = 0;
            for(index = 0; index < text.Length / conversionFactor; index++)
            {
                Console.WriteLine( intPointer[ index ] );
            }

            if( text.Length % conversionFactor != 0 )
            {
                intPointer[ index ] <<= sizeof( Int64 );
                intPointer[ index ] >>= sizeof( Int64 );

                Console.WriteLine( intPointer[ index ] );
            }
     }
}

解决方法

你几乎做对了. sizeof(char)== 2&& sizeof(int)== 4.循环转换因子必须是2,而不是4.它是sizeof(int)/ sizeof(char).如果你喜欢这种风格,你可以使用这个确切的表达. sizeof是一个鲜为人知的C#功能.

注意,如果长度不均匀,那么现在你丢失了最后一个字符.

关于性能:你做到这一点的方式和它一样便宜.

Hive where int/string <> int/int/string <> string cast类型转化/where自动过滤掉NULL,保留‘‘

Hive where int/string <> int/int/string <> string cast类型转化/where自动过滤掉NULL,保留‘‘

1 int/string <> int,会把string cast成 int ,不能转化为int的字符串都会cast成NULL,<>int也会把NULL值的记录过滤掉,''不是NULL故''保留在结果中 

select cast('' as int) --res7,结果是NULL
  • select cast(' ' as int) --res8,结果是NULL
  • select cast(null as int) -- 结果是NULL
  • select cast('1' as int) --结果是1
  • select cast('' as string) --结果是''
  • select *
  • from (
  • select 1 as c1
  • union all
  • select 2 as c1
  • union all
  • select '34' as c1
  • union all
  • select '3ab4' as c1
  • union all
  • select 'ab' as c1
  • union all
  • select '' as c1
  • union all
  • select ' ' as c1
  • union all
  • select null as c1
  • ) t1 where c1 <> 1 ; --res15,2行记录分别是2,34,不能转化为int的字符串都会cast成NULL,<>1会把NULL过滤掉
  • 今天关于将String转换为int。如果String为null,则将int设置为0将string转化为int的分享就到这里,希望大家有所收获,若想了解更多关于c + +不能将string转换为wstring、c – 使用boost spirit将String转换为int、c# – 重新解释将数组从string转换为int、Hive where int/string <> int/int/string <> string cast类型转化/where自动过滤掉NULL,保留‘‘等相关知识,可以在本站进行查询。

    本文标签:

    上一篇输入字符串“ 1”的java.lang.NumberFormatException(输入一个字符串java)

    下一篇使用Python在Windows中获取电池容量(python获取电池电量)