且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何比较substring中的字符串与java?

更新时间:2023-10-11 08:45:16

你好朋友,



我解决了它:)请标记它如果你愿意,也可以解决它并给它评分:)



这是代码:

Hi friend,

I Solved it :) Please mark it as solved and rate it too if you wish :)

Here's the code :
String body = "example....string...here..";

for (int loop = 0; loop < body.length() - 1; loop++)
{
    char cek1 = body.substring(loop, loop+1).charAt(0);
    char cek2 = body.substring(loop+1, loop+2).charAt(0);

    if (cek1 == '.' && cek2 == '.')
    {
        body = body.substring(0, loop) + body.substring(loop+2, body.length());
        loop = loop-1;
    }
}





我所做的是将单个字符串字符串类型转换为字符类型,然后比较它:)





有问候

Tushar Srivastava



What I did was converted the single charater String type to a character type and then compare it :)


With Regards
Tushar Srivastava

>

如果我正确理解您的代码,您试图删除单词中的。。但是你的代码很难理解。您应该使用正则表达式模式和匹配器来实现它。请参阅下面的示例代码。您可以在网上找到许多正则表达式教程。我在这里有一篇文章整数验证的代码实验 [ ^ ]



If I understand your code correctly, you are trying to remove the '.' in a word. But your code is hard to comprehend. You should use regex pattern and matcher to achieve it. See my sample code below. You can find many regex tutorials on the web. I have one article on this here Code Experiment on Integer Validation[^]

package com.peterleow;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test01 {
	
	public static void main(String[] args) {
		   
	    String body = "example....string...here..";
	    
	    System.out.println("Before : " + body);
	    
            // regex syntax for one or more '.' 
	    Pattern pattern2Remove = Pattern.compile("\\.+"); 
	    
	    Matcher matcher = pattern2Remove.matcher(body);
	    
	    while(matcher.find())
            {
                 String string2Remove = matcher.group();

                 body = body.replace(string2Remove, "");

                 System.out.println("After : " + body);
            } 
	}
}


如果你想比较字符串,你不能使用
If you want to compare string, you cannot use
if (cek1 == '.' && cek2 == '.')



你必须使用


you have to use

if (cek1.equals"." && cek2.quals".")



因为字符串是一个对象。当然,可以使用==来比较char:)


because string is an object. of course, it's fine to use "==" to compare char :)