在字符串中的两个单词之间添加填充或边距,可以通过编程语言中的字符串操作来实现。以下是一些常见编程语言的示例代码:
def add_spacing(text, word1, word2, spacing=' '):
words = text.split()
for i in range(len(words) - 1):
if words[i] == word1 and words[i + 1] == word2:
words[i] += spacing
words[i + 1] = spacing + words[i + 1]
return ' '.join(words)
text = "This is a sample text with two words."
word1 = "sample"
word2 = "text"
spaced_text = add_spacing(text, word1, word2, spacing='***')
print(spaced_text)
function addSpacing(text, word1, word2, spacing = ' ') {
const words = text.split(' ');
for (let i = 0; i < words.length - 1; i++) {
if (words[i] === word1 && words[i + 1] === word2) {
words[i] += spacing;
words[i + 1] = spacing + words[i + 1];
}
}
return words.join(' ');
}
const text = "This is a sample text with two words.";
const word1 = "sample";
const word2 = "text";
const spacedText = addSpacing(text, word1, word2, '***');
console.log(spacedText);
public class AddSpacing {
public static String addSpacing(String text, String word1, String word2, String spacing) {
String[] words = text.split(" ");
for (int i = 0; i < words.length - 1; i++) {
if (words[i].equals(word1) && words[i + 1].equals(word2)) {
words[i] += spacing;
words[i + 1] = spacing + words[i + 1];
}
}
return String.join(" ", words);
}
public static void main(String[] args) {
String text = "This is a sample text with two words.";
String word1 = "sample";
String word2 = "text";
String spacedText = addSpacing(text, word1, word2, "***");
System.out.println(spacedText);
}
}
通过上述方法,可以在字符串中的两个指定单词之间添加所需的填充或边距,从而实现特定的文本格式化需求。
领取专属 10元无门槛券
手把手带您无忧上云