首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用内部包含x10的字符串比较和替换x10变量

如何用内部包含x10的字符串比较和替换x10变量
EN

Stack Overflow用户
提问于 2018-03-10 07:43:37
回答 2查看 99关注 0票数 1

我一直在尝试做的事情:

代码语言:javascript
复制
double x10 = 2.4;  
String str = "The value of a variable is x10";  
int c = 0;  
while(c<str.length) #Here digit means a valid Number  
if(str.charAt[c]==digit && str.charAt[c+1]==digit){  
  str.charAt[c] = Double.toString(x10);
}  

所需输出:

代码语言:javascript
复制
The value of a variable is 2.4

问题:

代码语言:javascript
复制
The problem is that it doesn't seems to be comparing 10 in a String,  
so that it can replace the x10 in the string with the value of variable x10.

有没有其他方法可以达到预期目标?

代码语言:javascript
复制
it works fine with variable x(1-9) but when it exceeds x10 & greater it stucks.  
Didn't found anything relevant to my problem.  

任何帮助都将受到高度鼓励!

EN

回答 2

Stack Overflow用户

发布于 2018-03-10 08:44:38

我假设你在C#。您可以使用接受MatchEvaluator委托的Regex.Replace变体。假设您的值是double[] values格式的,并且它们的替换在值上是一次性的(例如,"x1“对应于values[0]),您可以这样做:

代码语言:javascript
复制
var ans = Regex.Replace(str, @"x(\d+)", m => values[Convert.ToInt32(m.Groups[1].Value)-1].ToString());
票数 0
EN

Stack Overflow用户

发布于 2018-03-11 07:36:27

经过如此多次的尝试,才能达到预期的输出。我终于想出了解决它的方法。

代码语言:javascript
复制
    String str = "x12",str2 = "x1";
    if(str2.matches("x[0-9]{1}")==true){

        int var = Integer.parseInt(str.substring(1,2));
        System.out.println(var);

    }else{
        System.out.println("Not Found!");

    }if(str.matches("x[0-9]{2}")==true){

        int var = Integer.parseInt(str.substring(1,2));
        int var2 = Integer.parseInt(str.substring(2,3));
        var = var * 10 + var2;
        System.out.println(var);

    }else{
        System.out.println("Not Found!");
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49203788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档