Java 我想用另一根弦替换弦的一部分
我刚刚开始,我已经创建了部分代码,部分a找到了用户在主字符串(代码中的行)中查找的字母(或短语)的int位置。b部分计算字母(或短语)出现的次数。在下一部分(不创建新方法)中,我希望如果s(用户正在查看的内容)是一个“u”,则用其他类似“-”的内容替换它们,然后将其打印出来。 这是我的密码:Java 我想用另一根弦替换弦的一部分,java,Java,我刚刚开始,我已经创建了部分代码,部分a找到了用户在主字符串(代码中的行)中查找的字母(或短语)的int位置。b部分计算字母(或短语)出现的次数。在下一部分(不创建新方法)中,我希望如果s(用户正在查看的内容)是一个“u”,则用其他类似“-”的内容替换它们,然后将其打印出来。 这是我的密码: import java.util.Scanner; import java.util.concurrent.CountDownLatch; public class Main { //my code ac
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
public class Main
{
//my code acomplishes the goal but it dose not do it the way you are asking for, sorry:(
public static String line; // The line to format
public static void main(String [] arrrgs)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a master String:");
String line = input.nextLine();
System.out.println("Enter a letter to look for:");
String s = input.nextLine();
System.out.println("Enter a starting location:");
int begin = input.nextInt();
//part a
int loc = begin;
while (loc != line.length()){
loc++;
if (loc != line.length()){
if (s.matches(line.substring(loc, loc + 1))){
System.out.println(s + " appears at " + (loc + 1));//prints location of strin except for first one
}
}
}
int oomf = 1;
if(s.matches(line.substring(0, 1)))//looks at first letter
System.out.println(oomf); //prints if nesasary
//part b
int count = 0;
int timer = begin;
while (timer != line.length()){
timer++;
if (timer != line.length()){
if (s.matches(line.substring(timer, timer + 1))){
count++;
}
}
}
System.out.println(s +"apears " + count + " times.");
}
}
正如您从注释中看到的,有JavaAPI来操作字符串 这里是一个如何做到这一点的例子
public static void main(String[] args) {
String testString = "Hello _ World _";
// Replace with Java API:
System.out.println(testString.replace('_', '-'));
// Replace using own naive code:
String newString = "";
for(int i = 0; i < testString.length(); i++) {
if(testString.charAt(i) == '_') {
newString += "-";
} else {
newString += testString.charAt(i);
}
}
System.out.println(newString);
}
publicstaticvoidmain(字符串[]args){
String testString=“Hello\uuworld”;
//替换为Java API:
System.out.println(testString.replace(“”,“-”);
//使用自己的朴素代码替换:
字符串newString=“”;
对于(int i=0;i
你应该能够在你的计划中采用这一点
请注意,在java中,所有字符串都是不可变的。这意味着,一旦创建了字符串,就不能对其进行更改。因此,您必须使用更改创建新字符串
这就是为什么必须使用replace()的返回值。您的原始字符串将保持不变。如果我只想每隔一个替换一个呢_