5.2字符串中数字子串的求和

题目

给定一个字符串str,求其中全部数字串所代表的数字之和。

要求:

  1. 忽略小数点字符。
  2. 如果紧贴数字子串的左侧出现字符“-”,当连续出现的数量为奇数时,数字视为负;连续出现的数量为偶数时,数字视为正。
代码实现
public int numSum(String str) {
    if (str == null) {
        return 0;
    }

    int res = 0;
    int num = 0;
    boolean posi = true;
    int cur = 0;

    for (int i = 0; i < str.length(); i++) {
        cur = str.charAt(i) - '0';
        if (cur < 0 || cur > 9) {
            res += num;
            num = 0;
            if (str.charAt(i) == '-') {
                if (i > 0 && str.charAt(i - 1) == '-') {
                    posi = !posi;
                } else {
                    posi = false;
                }
            } else {
                posi = true;
            }
        } else {
            num = num * 10 + (posi ? cur : -cur);
        }
    }
    res += num;

    return res;
}
在C#,查找字符串子串可以通过多种方法实现,这些方法提供不同的功能和效率。以下是一些常用的字符串查找方法: 1. `IndexOf` 方法:这是一个非常常用的方法,用于查找子串字符串位置。如果找到子串,它会返回子串的起始索引;如果没有找到,则返回 -1。 示例代码: ```csharp string source = "Hello, world!"; int index = source.IndexOf("world"); // 返回索引为 7 ``` 2. `LastIndexOf` 方法:与 `IndexOf` 类似,但它是从字符串的末尾开始搜索,并返回子串最后出现的位置。 3. `Contains` 方法:检查字符串是否包含指定的子串。它返回一个布尔值。 示例代码: ```csharp string source = "Hello, world!"; bool contains = source.Contains("world"); // 返回 true ``` 4. `StartsWith` 和 `EndsWith` 方法:分别用来检查字符串是否以特定的子串开始或结束。 5. 使用正则表达式:`Regex` 类可以用来查找字符串的匹配项,适用于复杂的模式匹配。 示例代码: ```csharp using System.Text.RegularExpressions; string source = "Hello, world!"; Match match = Regex.Match(source, "world"); if (match.Success) { int startIndex = match.Index; // 返回索引为 7 } ``` 6. `Substring` 方法:虽然这个方法本身不查找子串,但它经常与 `IndexOf` 或其他方法一起使用来获取子串。 示例代码: ```csharp string source = "Hello, world!"; int index = source.IndexOf("world"); string sub = source.Substring(index); // 返回 "world!" ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值